Java Data Types
Java is a statically typed language, meaning every variable must be declared with a data type. Data types define the kind of data a variable can hold.
π° Categories of Data Typesβ
Java data types are divided into two main categories:
- Primitive Data Types
- Non-Primitive (Reference) Data Types
π§± 1. Primitive Data Typesβ
Java has 8 built-in (primitive) data types:
| Data Type | Size | Description | Example |
|---|---|---|---|
| byte | 1 byte | Stores whole numbers from -128 to 127 | byte b = 100; |
| short | 2 bytes | Stores whole numbers from -32,768 to 32,767 | short s = 30000; |
| int | 4 bytes | Stores whole numbers from -2^31 to 2^31-1 | int i = 500000; |
| long | 8 bytes | Stores very large whole numbers | long l = 10000000000L; |
| float | 4 bytes | Stores fractional numbers (6-7 decimal digits) | float f = 5.75f; |
| double | 8 bytes | Stores fractional numbers (15 decimal digits) | double d = 19.99; |
| boolean | 1 bit | Stores true or false values | boolean isJavaFun = true; |
| char | 2 bytes | Stores a single character | char grade = 'A'; |
π§ 2. Non-Primitive (Reference) Data Typesβ
These refer to objects and include:
- Strings
- Arrays
- Classes
- Interfaces
String name = "InitCareer";
int[] numbers = {1, 2, 3};
Non-primitive types are created by the programmer and have methods associated with them.
π Real World Exampleβ
Think of primitive types as basic ingredients like rice, sugar, and salt. Non-primitive types are like recipes you create using those ingredients.
π§ Explain Like I'm Fiveβ
Primitive types are like LEGO blocks. Each one is a fixed shape and color. You can combine them to build something bigger (non-primitive types), like a LEGO house or car.
π‘ Fun Factβ
Java's primitive types are not objects, which makes them faster for computationβgreat for performance-critical applications like games or real-time systems.
π§ͺ Exerciseβ
- Declare a variable of each primitive type.
- Print their default values.
- Create a String and an array, then print them.
public class DataTypesExample {
public static void main(String[] args) {
byte b = 10;
short s = 1000;
int i = 100000;
long l = 10000000000L;
float f = 5.75f;
double d = 19.99;
boolean bool = true;
char c = 'A';
String name = "InitCareer";
int[] numbers = {1, 2, 3};
System.out.println("Byte: " + b);
System.out.println("Short: " + s);
System.out.println("Int: " + i);
System.out.println("Long: " + l);
System.out.println("Float: " + f);
System.out.println("Double: " + d);
System.out.println("Boolean: " + bool);
System.out.println("Char: " + c);
System.out.println("String: " + name);
System.out.println("Array element: " + numbers[0]);
}
}