Data Types in Java
Source: Dev.to
Data types specify the different sizes and values that can be stored in a variable. Java is a statically‑typed language, so every variable must be declared with its type before it is used.
Primitive Data Types
- byte – 8‑bit signed integer. Range:
-128to127. - short – 16‑bit signed integer. Range:
-32,768to32,767. - int – 32‑bit signed integer. Range:
-2,147,483,648to2,147,483,647. - long – 64‑bit signed integer. Range:
-9,223,372,036,854,775,808to9,223,372,036,854,775,807. - float – 32‑bit single‑precision floating‑point number.
- double – 64‑bit double‑precision floating‑point number.
- boolean – Represents
trueorfalse. - char – 16‑bit Unicode character.
int a = 10;
float f = 3.14f;
boolean flag = true;
char letter = 'A';
Non‑Primitive (Reference) Data Types
- Classes – Templates for creating objects.
- Interfaces – Contracts that define methods for classes.
- Arrays – Collections of elements of the same data type.
- String – Represents a sequence of characters.
String name = "aaa";
int[] numbers = {1, 2, 3, 4};
Primitive vs Non‑Primitive Data Types
| Aspect | Primitive Types | Non‑Primitive Types |
|---|---|---|
| Memory | Stored on the stack | Stored on the heap |
| Speed | Faster access and manipulation | Slower due to reference handling |
| Example | int a = 10; | String name = "aaa"; |
Both categories are essential: primitives provide efficient, low‑level data handling, while non‑primitives enable more complex structures and behavior.