Data Types
Overview
Data types define exactly what kind of data a variable box can hold, and how much physical space it takes up in the computer's memory. Imagine you are packing for a trip: you wouldn't use a massive suitcase just to pack a single toothbrush. Similarly, Java gives you different sizes of boxes for different sizes of numbers.
Java has two main categories of data types: Primitives (the simple, built-in building blocks) and Non-Primitives (complex objects like Strings or Arrays).
1. Primitive Types (The Basics)
These are the 8 foundational data types in Java. They are highly efficient because they store simple values directly in memory. The most common ones you will use are `int` (for whole numbers), `double` (for decimals), `boolean` (for true/false), and `char` (for a single letter).
2. Why so many number types?
Java has 4 types for whole numbers: `byte`, `short`, `int`, and `long`. It also has 2 for decimals: `float` and `double`. This allows developers to save memory in massive applications. However, 99% of the time, you will just use `int` and `double`!
3. Type Casting (Converting)
Sometimes you need to convert one type to another (like turning a decimal into a whole number by chopping off the decimal part). This is called 'casting'.
Syntax
Here are the most frequently used primitives in everyday coding.
int age = 20; // Whole numbers (up to ~2 billion)
double price = 19.99; // Decimal numbers
boolean isPassed = true;// true or false ONLY
char grade = 'A'; // A single character (use single quotes!)Converting a larger box (double) into a smaller box (int) requires manual casting.
double exactPrice = 9.99;
// We manually cast (convert) the double to an int.
// Note: It doesn't round up! It just chops off the decimal.
int roundedPrice = (int) exactPrice;
System.out.println(roundedPrice); // Prints: 9Common Pitfalls
- Forgetting the 'f' suffix on `float` or 'L' on `long`. If you write `float x = 1.5;`, Java will complain because it assumes all decimals are `double` by default.
- Losing data during casting. If you cast `10.99` to an `int`, you get `10`, losing the `.99`.
Interview Tips
- Never use `double` or `float` for money/currency calculations in the real world! They suffer from rounding errors. Always mention `BigDecimal` if an interviewer asks about currency.
Real-World Example
Choosing the right data type ensures your app doesn't crash or behave weirdly.
public class VideoGameStats {
public static void main(String[] args) {
// Use 'long' for huge numbers like global player counts
long totalGlobalPlayers = 8000000000L; // Notice the 'L' at the end!
// Use 'float' if you want to save memory on decimals
float characterSpeed = 4.5f; // Notice the 'f' at the end!
boolean hasWon = false;
}
}