Java Data Types
A data type describes the kind of value a variable can hold and what you are allowed to do with it. Java splits every type into two families: the eight built-in primitive types, and reference types such as String and arrays that point to objects.
The two families of types
Primitive types are the simplest building blocks. They store a raw value directly, they are always lowercase, and there are exactly eight of them. Reference types, by contrast, store the address of an object that lives elsewhere in memory; String, arrays, and every class you write are reference types.
- Primitive types: byte, short, int, long, float, double, char, and boolean.
- Reference types: String, arrays, and objects of any class.
- Primitives can never be null, while reference types can.
- Primitive names are lowercase; reference type names start with a capital letter.
The eight primitive types
Each primitive type reserves a fixed amount of memory, which sets the range of values it can hold. Knowing these sizes helps you pick a type that is large enough for your data without wasting space.
Choosing a type in practice
Most everyday code uses just a few of these. Reach for int for whole numbers, double for anything with a decimal point, boolean for yes-or-no flags, and String for text. The narrower types like byte and short exist mainly to save memory when you have huge amounts of data.
A mix of primitive types
public class Main {
public static void main(String[] args) {
int items = 12;
double weight = 4.75;
char section = 'B';
boolean inStock = true;
System.out.println(items + " items, " + weight + " kg, section " + section + ", in stock: " + inStock);
}
}Default values
When a primitive is a field of a class and you do not set it, Java gives it a sensible default: zero for numbers, false for boolean, and the null character for char. Local variables inside methods, however, get no default and must be assigned before use.
String is a reference type
public class Main {
public static void main(String[] args) {
String message = "Data types in Java";
System.out.println(message.length());
}
}Exercise: Java Data Types
What type does Java assign to a decimal literal like 3.14 by default?