Variables and their types
A variable holds a value under a name. Every Java variable also has a type, which says what kind of value it can hold. Four types cover most of what you'll need for now:
| Type | Holds | Examples |
|---|---|---|
int |
whole numbers | 3, -12, 2026 |
double |
numbers with a decimal point | 0.45, -3.5, 2.0 |
boolean |
true or false | true, false |
String |
text | "apple", "Hello!" |
A variable is created by writing its type, its name and its first value:
int apples = 12;
double price = 0.45;
boolean inStock = true;
String fruit = "apple";
System.out.println(fruit + ": " + apples + " at " + price);
System.out.println("In stock: " + inStock);
apple: 12 at 0.45
In stock: trueAs the last two lines show, + joins numbers and booleans into text too: "In stock: " + inStock becomes In stock: true.
The type decides what fits
A variable can only hold values that fit its type. Putting a decimal number into an int would lose the part after the point, so Java refuses to compile it:
public class Main {
public static void main(String[] args) {
int price = 4.99;
System.out.println(price);
}
}
Main.java:3: error: incompatible types: possible lossy conversion from double to int
int price = 4.99;
^
1 errorThe other way round is fine: double distance = 5; compiles, because a whole number fits in a double without losing anything (it becomes 5.0).
Note the capital S in String: it's a class, like Scanner, while int, double and boolean are built into the language and written in lower case.