Java Data Types
Java has two families of types: primitives and references.
Primitive types (8 of them)
Primitives store actual values directly in memory. They're fast, fixed-size, and have a default value if not initialized in a class.
| Type | Size | Range | Default | Example |
|---|---|---|---|---|
byte | 8 bits | −128 to 127 | 0 | byte b = 100; |
short | 16 bits | −32,768 to 32,767 | 0 | short s = 30000; |
int | 32 bits | ≈ ±2.1 billion | 0 | int i = 1_000_000; |
long | 64 bits | ≈ ±9.2 × 10¹⁸ | 0L | long l = 99999999L; |
float | 32 bits | ~7 decimal digits | 0.0f | float f = 3.14f; |
double | 64 bits | ~15 decimal digits | 0.0 | double d = 3.14159; |
boolean | 1 bit | true / false | false | boolean ok = true; |
char | 16 bits | Unicode character | '\u0000' | char c = 'A'; |
int for whole numbers, double for decimals, boolean for true/false, String for text. Reach for long, byte, short, or float only when you have a specific reason.
Numeric literals
int hex = 0xFF; // hexadecimal = 255 int binary = 0b1010; // binary = 10 int million = 1_000_000; // underscores for readability long big = 123456789L; // L suffix for long float rate = 3.14f; // f suffix for float
Reference types
Anything that's not a primitive is a reference type. Variables of reference types store a pointer to the object, not the object itself. Objects live on the heap; references can be null.
String name = "Raman"; // String int[] numbers = {1, 2, 3}; // array var list = new ArrayList<String>(); // custom class String empty = null; // can be null
Type casting
Converting between types. Two flavors:
Implicit (widening) — automatic
int i = 100; long l = i; // int → long, automatic double d = i; // int → double, automatic
Explicit (narrowing) — risk of data loss
double d = 3.99; int i = (int) d; // 3 (decimal lost — truncated, not rounded) long big = 9_000_000_000L; int small = (int) big; // data loss — exceeds int range
Wrapper classes
Each primitive has a corresponding object wrapper: int → Integer, double → Double, boolean → Boolean. Use them when you need to put a primitive into a collection like List<Integer> (collections only hold objects).
Java auto-converts between primitives and wrappers (called autoboxing and unboxing) — it just works.