Data types specify the different sizes and values that can be stored in the variable. In Java, data types are divided into two main categories: Primitive and Non-Primitive.
Before diving into details, it's important to understand the high-level classification:
int, char, boolean, etc. They store simple values.Java has 8 primitive data types, each with a fixed size in memory. This ensures portability across different hardware.
| Data Type | Size | Description | Range / Value |
|---|---|---|---|
byte |
1 byte | Very small whole numbers | -128 to 127 |
short |
2 bytes | Small whole numbers | -32,768 to 32,767 |
int |
4 bytes | Standard whole numbers | -2.1B to 2.1B |
long |
8 bytes | Huge whole numbers | -9 quintillion to 9 quintillion |
float |
4 bytes | Decimal numbers | 6-7 decimal digits precision |
double |
8 bytes | High precision decimals | 15 decimal digits precision |
boolean |
1 bit | Logical state | true or false |
char |
2 bytes | Single character/Unicode | 'A', 'B', '\u0041' |
Even though they all store whole numbers, you should choose based on the size of the data to save memory.
Use float or double when you need numbers with a fractional part (decimals). By default, every decimal in Java is a double.
You can also use 'e' to indicate the power of 10:
float f1 = 35e3f; // 35000.0
Unlike C/C++, Java uses 2 bytes for char because it supports Unicode. This allows Java to represent characters from almost all global languages.
Non-primitive types refer to objects. They are called reference types because they store the memory address of the data, not the value itself.
| Feature | Primitive | Non-Primitive |
|---|---|---|
| Definition | Predefined in Java | Created by programmer |
| Value | Always has a value | Can be null |
| Size | Depends on type | All have same address size |
Understanding data types is the key to writing memory-efficient code. But what happens if you want to store a double value into an int variable? That process is called Type Casting, and that is exactly what we will cover in the next chapter!