Java Data Types
Data types specify the size and type of values a variable can store. Java has two groups: primitive and non-primitive.
Primitive Data Types
| Type | Size | Default | Example |
|---|---|---|---|
| byte | 1 byte | 0 | byte b = 10; |
| short | 2 bytes | 0 | short s = 500; |
| int | 4 bytes | 0 | int n = 1000; |
| long | 8 bytes | 0L | long l = 9000000000L; |
| float | 4 bytes | 0.0f | float f = 3.14f; |
| double | 8 bytes | 0.0d | double d = 3.14159; |
| char | 2 bytes | '\u0000' | char c = 'A'; |
| boolean | 1 bit* | false | boolean ok = true; |
*The JVM specification doesn't fix the exact size of boolean.
Non-Primitive Data Types
Also called reference types: String, arrays, classes and interfaces. They store a reference (address) to an object.
Type Casting
int a = 100;
double d = a; // widening (automatic)
System.out.println(d);
double x = 9.78;
int y = (int) x; // narrowing (manual)
System.out.println(y);
100.0
9
Track your progress through the Java course