Java Data Types
Java data types fall into two groups: primitive types, which hold simple values directly, and reference types, which point to objects such as String, arrays and your own classes.
The Eight Primitive Types
- byte: 8-bit whole number, -128 to 127
- short: 16-bit whole number, -32,768 to 32,767
- int: 32-bit whole number, about plus or minus 2.1 billion (the default choice)
- long: 64-bit whole number, add L to literals: 9_000_000_000L
- float: 32-bit decimal, about 7 digits of precision, add f: 3.14f
- double: 64-bit decimal, about 15 digits of precision (the default for decimals)
- boolean: true or false
- char: a single 16-bit Unicode character in single quotes: 'A'
Using Primitive Types
public class Main {
public static void main(String[] args) {
byte small = 100;
int items = 2_500;
long worldPopulation = 8_100_000_000L;
float temperature = 36.6f;
double pi = 3.141592653589793;
boolean isOpen = true;
char grade = 'A';
System.out.println(small + " " + items + " " + worldPopulation);
System.out.println(temperature + " " + pi);
System.out.println(isOpen + " " + grade);
System.out.println("Max int: " + Integer.MAX_VALUE);
}
}100 2500 8100000000 36.6 3.141592653589793 true A Max int: 2147483647
Integer Overflow
If a calculation goes beyond a type's range it silently wraps around. Use long, or Math.addExact which throws an exception on overflow, when numbers can get large.
public class Main {
public static void main(String[] args) {
int big = Integer.MAX_VALUE;
System.out.println(big + 1);
long safe = (long) big + 1;
System.out.println(safe);
}
}-2147483648 2147483648
Reference Types
Anything that is not a primitive is a reference type. The variable stores a reference to an object in memory. Reference types can be null, meaning they point to nothing, and they have methods you can call.
public class Main {
public static void main(String[] args) {
String word = "Java";
int[] scores = {90, 75, 82};
String nothing = null;
System.out.println(word.length());
System.out.println(scores.length);
System.out.println(nothing == null);
}
}4 3 true
Wrapper Classes
Each primitive has a wrapper class: Integer, Double, Boolean, Character and so on. Collections like ArrayList can only store objects, so Java automatically converts (autoboxes) int to Integer when needed.
Frequently asked questions
What is the difference between float and double in Java?
double has twice the precision of float and is the default type for decimal literals. Use double unless you have a specific memory reason to use float.
Is String a primitive type in Java?
No. String is a class, so it is a reference type, even though Java gives it special syntax like string literals and the + operator.
Should I use double for money in Java?
No, because double cannot represent many decimal fractions exactly. Use BigDecimal or store amounts as whole cents in a long.