Jan 24, 2026
## Chapter 4: Storing Data (Variables and Types)
When you’re writing a program, you need to store information—like a user’s name, their age, or the price of a shirt. In Java, we do this using **Variables**.
Think of a variable as a small box with a label on it. But Java is very strict: you must tell it exactly what kind of thing you’re going to put in that box. You can't put a shoe in a box labeled "eggs".
### The 8 Primitive Types (The Basics)
Java has 8 basic types. Most students only use `int` and `double`, but you should know the others because they save memory.
- **`byte`**: Very small (1 byte). Holds -128 to 127. Use it if you’re saving millions of small numbers.
- **`short`**: Small (2 bytes).
- **`int`**: The most common (4 bytes). Holds up to 2 Billion.
- **`long`**: For huge numbers (8 bytes). Use this for money or population.
- **`float`**: For decimals (4 bytes).
- **`double`**: For precise decimals (8 bytes). Use this for math.
- **`boolean`**: Just `true` or `false`.
- **`char`**: For a single letter like 'A' or '$'.
### Examples for Chapter 4:
**1. Basic (Creating boxes):**
```java
int studentsCount = 50;
double petrolPrice = 102.5;
char section = 'B';
boolean isClassOver = false;
```
*Teacher's comment:* Notice the names. I didn't write `int a = 50`. Use names that tell you *what* is inside the box.
**2. Common Mistake (The "Decimal in a Box" error):**
```java
int age = 20.5; // ERROR!
```
*Why this happens:* An `int` box is only for whole numbers. If you try to put `20.5` in it, Java says "Hey, I might lose information if I throw away that `.5`!" You must use `double` or `float` for this.
**3. Explanation-Focused (Reference Types vs Primitives):**
This is where students get confused.
- **Primitives** (like `int`) store the actual value in the box.
- **Reference Types** (like `String` or Arrays) don't store the value. They store the "Address" of where the value is.
*Analogy:* A primitive is like having cash in your pocket. A reference is like having a key to a locker. The cash is *right there*, but for the locker, you have to follow the key to find the stuff.
**4. Real-Life (The "Big Bill" problem):**
Imagine you are writing code for a bank.
```java
int totalAmount = 2000000000; // 2 Billion
totalAmount = totalAmount + 500000000; // Adding 0.5 Billion
System.out.println(totalAmount);
```
*Result:* You get a weird negative number!
*Why:* `int` only goes up to 2.1 Billion. If you go higher, it "wraps around" like a car's odometer. For money, always use `long` or a special class called `BigDecimal`.
**5. Future Hint (Type Casting):**
Sometimes you *want* to force a `double` into an `int`.
```java
double price = 99.99;
int roundedPrice = (int) price; // Result: 99
```
*Teacher's comment:* This is called "Casting". It's like taking a big object and squeezing it into a small box. You *will* lose the `.99`. We'll use this a lot when we talk about Objects and Inheritance later.