Java Data Types
- It specifies what kind of value a variable can store.
- DataType tells the size, range and nature of data stored in memory.
- In Java, data types are divided into two categories: primitive types and reference (non-primitive) types .
- They are stored directly in the stack memory.
- They have fixed sizes.
Primitive Data Types :
Primitive data types are the most basic data types, It holds single, simple values like numbers or characters.
There are the 8 primitive data types in Java:
| Data Type | Size | Example |
|---|---|---|
| byte | 1 byte | byte age = 25; |
| short | 2 bytes | short year = 2025; |
| int | 4 bytes | int marks = 95; |
| long | 8 bytes | long population = 8000000000L; |
| float | 4 bytes | float price = 99.99f; |
| double | 8 bytes | double pi = 3.14159; |
| char | 2 bytes | char grade = 'A'; |
| boolean | - | boolean isPassed = true; |
Example:
public class PrimitiveDataTypesDemo {
public static void main(String[] args) {
// byte (1 byte)
byte age = 25;
// short (2 bytes)
short year = 2025;
// int (4 bytes)
int marks = 95;
// long (8 bytes)
long population = 8000000000L;
// float (4 bytes)
float price = 99.99f;
// double (8 bytes)
double pi = 3.14159;
// char (2 bytes)
char grade = 'A';
// boolean (1 bit conceptually)
boolean isPassed = true;
// Printing all values
System.out.println("byte: " + age);
System.out.println("short: " + year);
System.out.println("int: " + marks);
System.out.println("long: " + population);
System.out.println("float: " + price);
System.out.println("double: " + pi);
System.out.println("char: " + grade);
System.out.println("boolean: " + isPassed);
}
}Non-Primitive (Reference) Data Types:
Non-Promitive or reference type dataType stores the reference(address) of an objects in the memory, it does not stores the actual value directly. It stores objects or complex data or we can say collection of values, not simple values like primitives.
Below are the reference type datatype :
- String
- Arrays
- Classes
- Interface
- Objects
Difference between Primitive and Non-primitive dataType:
| Primitive | Non-Primitive |
|---|---|
It stores the actual value directly | It stores a reference (address) of an object |
The size of the data is fix | The size of the data tynamically change |
It has default values | Can be null |
Predefined by the programming language | This is user-defined |
Stored data in Stack memory | Stored data in Heap memory |
See you in next page....🙂