Chapter 3: Variables and Data Types
1. What is a Variable? (The Most Important Concept)
A variable is like a named box or labeled container in your computer’s memory where you store data.
- You give it a name (so you can refer to it later)
- You decide what type of data it can hold (int, String, etc.)
- You put a value inside it
Real-life analogy: Think of variables like labeled jars in your kitchen:
- One jar labeled “sugar” → only sugar goes in it
- One labeled “salt” → only salt
- If you try to put sugar in the salt jar → mistake!
In Java, the type of the variable decides what kind of value is allowed.
2. Two Big Categories of Data Types in Java
Java has two main kinds of data types:
- Primitive Types (the basic building blocks — 8 of them)
- Reference Types (everything else — objects, arrays, Strings, etc.)
Let’s start with Primitives — they are simple, fast, and live directly in memory.
3. Primitive Data Types (with Examples & Memory Sizes)
| Type | What it Stores | Size (bits/bytes) | Range / Example Values | Default Value (if not initialized) | Real-life Analogy |
|---|---|---|---|---|---|
| byte | Very small whole numbers | 8 bits (1 byte) | -128 to 127 | 0 | Tiny jar for spices |
| short | Small whole numbers | 16 bits (2 bytes) | -32,768 to 32,767 | 0 | Small lunch box |
| int | Normal whole numbers (most used) | 32 bits (4 bytes) | -2,147,483,648 to 2,147,483,647 | 0 | Regular water bottle |
| long | Very large whole numbers | 64 bits (8 bytes) | -9 quintillion to +9 quintillion (add L at end) | 0L | Big 20L water can |
| float | Decimal numbers (less precise) | 32 bits (4 bytes) | ~6-7 decimal digits (add f at end) | 0.0f | Quick measurement (approx) |
| double | Decimal numbers (most precise) | 64 bits (8 bytes) | ~15 decimal digits (default for decimals) | 0.0 | Accurate scientific measurement |
| char | Single character (letter/symbol) | 16 bits (2 bytes) | Unicode characters: ‘A’, ‘न’, ‘₹’, ‘\u20B9’ | ” (empty) | One letter on a nameplate |
| boolean | True or False only | ~1 bit | true or false | false | Light switch (on/off) |
Important Notes:
- int is the most commonly used for whole numbers.
- double is the most commonly used for decimal numbers.
- char uses single quotes‘A’
- String is NOT primitive — it’s a reference type (we’ll cover it soon)
4. Declaring and Initializing Variables (with Examples)
Syntax:
|
0 1 2 3 4 5 6 7 8 9 10 |
type variableName; // declaration (just creating the box) variableName = value; // initialization (putting something in the box) // or in one line: type variableName = value; // declaration + initialization |
Real Examples (copy-paste into a new class and run!):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class VariablesDemo { public static void main(String[] args) { // Whole numbers (integers) int age = 25; byte smallNumber = 100; short populationSmallCity = 25000; long worldPopulation = 8100000000L; // Notice the L at the end! // Decimal numbers float heightInMeters = 5.9f; // Notice the f double salary = 85000.75; // Character char grade = 'A'; char rupeeSymbol = '\u20B9'; // Unicode for ₹ // Boolean boolean isRainingInMumbai = true; boolean isJavaFun = true; // Printing them System.out.println("My age: " + age); System.out.println("Salary: " + salary + " ₹"); System.out.println("Grade: " + grade); System.out.println("Raining today? " + isRainingInMumbai); } } |
Run this — you’ll see the values printed!
5. Reference Types (The Second Big Category)
Primitives store the actual value directly. Reference types store the memory address (reference/pointer) to the actual object.
Most common reference type you’ll use right now: String
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
String name = "Webliance"; String city = "Mumbai"; String favoriteQuote = "Keep learning, keep growing! 🚀"; // You can also do: String greeting; greeting = "नमस्ते!"; // Marathi hello |
Key differences:
| Feature | Primitive (int, double, etc.) | Reference (String, arrays, objects) |
|---|---|---|
| How value is stored | Actual value in variable | Reference (address) to the object |
| Default value | 0, 0.0, false, etc. | null |
| Can be null? | No | Yes |
| Methods? | No | Yes! (e.g. name.length()) |
Example:
|
0 1 2 3 4 5 6 |
String message = null; // perfectly valid — box is empty (no address) |
6. Type Casting & Conversion (Changing One Type to Another)
Sometimes you need to convert one type to another.
Two types:
A. Implicit Casting (Widening Conversion) — Automatic & Safe
Smaller type → bigger type (no data loss)
|
0 1 2 3 4 5 6 7 8 9 10 |
int marks = 85; double marksDouble = marks; // automatic! 85.0 float f = 10.5f; double d = f; // automatic |
B. Explicit Casting (Narrowing Conversion) — You must tell Java
Bigger → smaller (possible data loss)
|
0 1 2 3 4 5 6 7 8 9 10 |
double salary = 99999.99; int salaryInt = (int) salary; // 99999 (decimal part lost!) double pi = 3.14159; int piInt = (int) pi; // 3 |
Example with risk:
|
0 1 2 3 4 5 6 7 |
int bigNumber = 130; byte small = (byte) bigNumber; // -126 (overflow! byte max is 127) |
Tip: Always be careful with narrowing — you can lose data!
7. Constants (Values That Never Change)
Use final keyword — like a locked box that can’t be changed once filled.
|
0 1 2 3 4 5 6 7 8 9 10 |
final double PI = 3.14159; final String COUNTRY = "India"; final int MAX_USERS = 1000; // PI = 3.2; // ERROR! Cannot reassign final variable |
Convention: Constants are written in ALL_CAPS_WITH_UNDERSCORES
8. Scope of Variables (Where They Live and Die)
Local variables (declared inside a method):
- Live only inside that method/block
- Must be initialized before use
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public static void main(String[] args) { int x = 10; // local to main if (true) { int y = 20; // local to this block System.out.println(x + y); // OK } // System.out.println(y); // ERROR! y is dead outside the block } |
Class-level (instance/static) — we’ll cover later when we do OOP.
Quick Recap Table (Your Cheat Sheet)
| Concept | Example | Key Point |
|---|---|---|
| Primitive | int age = 28; | Fast, fixed size, actual value |
| Reference | String name = “Webliance”; | Can be null, has methods |
| Final constant | final double GST = 18.0; | Cannot change once set |
| Widening cast | double d = 100; | Automatic |
| Narrowing cast | int i = (int) 99.99; | Manual, possible data loss |
| Scope | Variable inside {} dies after } | Local variables must be initialized |
Homework for You (Try These!)
- Create a program called PersonalInfo.java
- Declare variables for: your name (String), age (int), height in cm (double), isStudent (boolean), favoriteNumber (long)
- Print all of them nicely
- Try this:
Java012345678double tempCelsius = 36.5;int tempInt = (int) tempCelsius;System.out.println(tempInt); // What do you get?
- Create a constant final int SPEED_LIMIT_MUMBAI = 80; and try changing it — see the error!
You’re doing fantastic! Variables are the foundation of everything in programming. Once you’re comfortable here, the rest becomes easy.
