Master the foundation of Java programming through comprehensive examples and visual learning
By the end of this lesson, you will:
<aside> 🏗️
Java Type System Overview
Java has a two-tier type system: Primitives (stored directly in memory) and Reference Types (stored as object references in heap memory).
</aside>
Stack Memory | Heap Memory
---------------------------|---------------------------
int age = 25; | String name = "John";
double salary = 50000.0; | ┌─────────────────┐
boolean isActive = true; | │ String Object │
| │ value: "John" │
Reference Variables: | └─────────────────┘
String name ────────────────────→ Heap Reference
| Type | Size (bits) | Range | Default Value | Real-World Use Case |
|---|---|---|---|---|
byte |
8 | -128 to 127 | 0 | Image pixel values, small counters |
short |
16 | -32,768 to 32,767 | 0 | Audio samples, temperature readings |
int |
32 | -2,147,483,648 to 2,147,483,647 | 0 | User IDs, counts, array indices |
long |
64 | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 0L | Timestamps, large file sizes, population counts |
float |
32 | IEEE 754 (±3.4 × 10³⁸) | 0.0f | Graphics coordinates, scientific calculations |
double |
64 | IEEE 754 (±1.7 × 10³⁰⁸) | 0.0d | Financial calculations, GPS coordinates |
// Real-world application of different data types
public class Student {
// Using appropriate data types for different purposes
private byte semester; // 1-8 (fits in byte range)
private short courseCount; // Number of courses (0-500)
private int studentId; // Unique identifier
private long phoneNumber; // Phone numbers (large numbers)
private float gpa; // Grade Point Average (precision adequate)
private double tuitionFee; // Financial data (high precision needed)
private boolean isActive; // Status flag
private char grade; // Single character grade (A-F)
// Constructor demonstrating type usage
public Student(int id, String name, byte semester) {
this.studentId = id;
this.semester = semester;
this.isActive = true;
this.courseCount = 0;
this.gpa = 0.0f;
this.tuitionFee = 25000.50; // Default tuition
this.phoneNumber = 1234567890L; // Note the 'L' suffix
}
// Method showing type conversions
public void updateGPA(double newGPA) {
// Explicit cast from double to float
this.gpa = (float) newGPA;
// Determine letter grade based on GPA
if (newGPA >= 3.7) this.grade = 'A';
else if (newGPA >= 3.0) this.grade = 'B';
else if (newGPA >= 2.0) this.grade = 'C';
else this.grade = 'F';
}
}