Variables and types
Declare values with the right type, and know why 0.1 + 0.2 is not 0.3.
Open this lesson in the learning hubKey points
- Java has eight primitives:
int,long,double,float,boolean,char,byte,short. - A primitive variable holds the value itself. Every other variable holds a reference to an object.
- Default to
intfor whole numbers anddoublefor decimals. Long literals need anL:9_000_000_000L. doubleis binary floating point, so0.1 + 0.2is not exactly0.3. UseBigDecimalfor money.- Overflow is silent.
Integer.MAX_VALUE + 1wraps around to the most negative int. var(Java 10+) infers the type of a local variable. The type is still fixed at compile time.
Example
public class Main {
public static void main(String[] args) {
int count = 42;
long big = 9_000_000_000L;
double price = 19.99;
boolean active = true;
char grade = 'A';
String name = "Ada";
System.out.println(name + " bought " + count + " items at " + price);
System.out.println("int max = " + Integer.MAX_VALUE);
System.out.println("int overflow = " + (Integer.MAX_VALUE + 1));
System.out.println("long value = " + big);
System.out.println("0.1 + 0.2 = " + (0.1 + 0.2));
System.out.println("grade + 1 = " + (grade + 1) + " as char: " + (char) (grade + 1));
System.out.println("active = " + active);
var scores = new java.util.ArrayList<Integer>();
scores.add(90);
System.out.println("var infers ArrayList<Integer>: " + scores);
}
}
Primitives hold a value; everything else holds a reference to an object.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.