Java Data Types π¶
Mentor's Note: Java is a "Statically Typed" language. This means you must tell Java exactly what kind of item you are putting in a box, and you can't change your mind later! π‘
π The Scenario: The Labeled Warehouse π¦¶
Imagine you are a warehouse manager.
- The Logic:
- You have Small Boxes for single numbers (byte). π’
- Large Boxes for massive numbers (long). π’
- Padded Boxes for fragile decimals (double). π²
- Check-mark Boxes for Yes/No (boolean). β
- The Result: By using the right size box, you save space and prevent "items" from breaking. In Java, this is why we have 8 Primitive Types. β
π Concept Explanation¶
1. Primitive Data Types (Simple)¶
These are built-in and have a fixed size.
| Type | Size | Range / Purpose |
|---|---|---|
int |
4 bytes | Whole numbers (-2.1B to 2.1B) |
double |
8 bytes | Decimals (Most precise) |
char |
2 bytes | Single letter (e.g., 'A') |
boolean |
1 bit | true or false |
2. Reference Data Types (Complex)¶
These point to "Objects." They can hold complex data and have their own methods.
- Examples: String, Arrays, Classes.
- Default Value: Primitives default to 0/false; Reference types default to null. π«
π¨ Visual Logic: The Storage Map¶
graph TD
A[Java Data Types] --> B[Primitive]
A --> C[Reference]
B --> B1[Numeric: int, long, double]
B --> B2[Logical: boolean]
B --> B3[Character: char]
C --> C1[String π]
C --> C2[Arrays π¦]
C --> C3[Objects π€]
π» Implementation: The Type Lab¶
// π Scenario: Storing a Student Record
// π Action: Using different data types
public class Main {
public static void main(String[] args) {
// π¦ Labeled Boxes
int rollNo = 101;
double percentage = 95.5;
char grade = 'A';
boolean isPassed = true;
String name = "Vishnu"; // Reference Type π
System.out.println(name + " (Roll: " + rollNo + ") Grade: " + grade);
}
}
// ποΈ Outcome: "Vishnu (Roll: 101) Grade: A"
π Sample Dry Run¶
| Step | Instruction | Variable | Memory Size | Value |
|---|---|---|---|---|
| 1 | int x = 5; |
x |
4 Bytes | 5 π¦ |
| 2 | double y = 5.5; |
y |
8 Bytes | 5.5 π¦ |
| 3 | String s = "Hi"; |
s |
Pointer | "Hi" (in Pool) π |
π Technical Analysis¶
- Precision: Always prefer
doubleoverfloatfor financial data to avoid rounding errors. π° - The String Pool: Java doesn't create a new String object if you use the same text twiceβit reuses the existing one to save memory! π§
π― Practice Lab π§ͺ¶
Task: The Price Tag
Task: Create variables for a product_price (decimal), quantity (whole number), and currency_symbol (character). Print them together.
Hint: double, int, and char. π‘
π‘ Pro Tip: "Type is a character, but data is its personality." - Anonymous