Understanding Java Data Types: Primitives and References
Java employs data types to specify the kind of values variables can hold, determining their storage format and valid range. These types are categorized into two main groups: primitive data types and reference data types.
Primitive Data Types
Primitive types store simple values and are divided into four categories:
1. Integer Types
byte: 8-bit (-128 to 127)short: 16-bit (-32,768 to 32,767)int: 32-bit (-2³¹ to 2³¹-1)long: 64-bit (-2⁶³ to 2⁶³-1)
int count = 100;
long population = 7_900_000_000L;
2. Flaoting-Point Types
float: 32-bit (~6-7 decimal digits)double: 64-bit (~15 decimal digits)
float piApprox = 3.1416f;
double precisePi = 3.141592653589793;
3. Character Type
char: 16-bit Unicode character
char initial = 'J';
4. Boolean Type
boolean:trueorfalse
boolean isActive = true;
Reference Data Types
Reference types store memory addresses of objects rather than values directly:
1. Class Types
User-defined types that create objects:
class Vehicle {
String model;
int year;
}
Vehicle car = new Vehicle();
car.model = "Tesla";
car.year = 2023;
2. Interface Types
Contracts for implementing classes:
interface Drawable {
void render();
}
class Square implements Drawable {
public void render() {
System.out.println("Drawing square");
}
}
Drawable shape = new Square();
shape.render();
3. Array Types
Fixed-size collections of elements:
double[] temperatures = {22.5, 19.8, 25.3};
String[] colors = {"Red", "Green", "Blue"};
4. Enum Types
Predefined constant sets:
enum Status { NEW, PROCESSING, COMPLETED }
Status current = Status.PROCESSING;
Type Conversion Features
Autoboxing
Automatic primitive-to-wrapper conversion:
int value = 50;
Integer boxed = value; // Autoboxing
Unboxing
Automatic wrapper-to-primitive conversion:
Integer wrapped = 75;
int extracted = wrapped; // Unboxing