Variables and Constants

Loading concept...

🏠 Variables in Java: Your Code’s Magic Storage Boxes

Imagine you have a magical house with different rooms. Each room can hold special things, and some rooms are private (only you can enter), some are shared with family, and some are open to everyone in the neighborhood!

Variables in Java work exactly like these rooms! They’re containers that store information, and where you put them decides who can use them.


🎯 What Are Variables?

A variable is like a labeled box where you keep something important.

int age = 10;
String name = "Emma";
  • age is a box labeled “age” holding the number 10
  • name is a box labeled “name” holding the word “Emma”

Simple, right? Now let’s see the different TYPES of rooms (scopes) where these boxes can live!


🚪 Local Variables: Your Private Bedroom

Local variables live inside a method—like toys that stay in YOUR bedroom. Nobody else can touch them!

public void playGame() {
    int score = 0;  // Only exists here!
    score = score + 10;
    System.out.println(score);
}
// score doesn't exist out here!

🔑 Key Rules:

  • Born when the method starts
  • Die when the method ends
  • Must be given a value before using
  • Only that method can see them
graph TD A[Method Starts] --> B[Local Variable Created] B --> C[Variable Used Inside Method] C --> D[Method Ends] D --> E[Variable Destroyed!]

🌟 Real Example:

public void countApples() {
    int apples = 5;      // Local variable
    apples = apples + 3; // Now 8
    System.out.println("Apples: " + apples);
}
// Try to use 'apples' here? ERROR!

🏡 Instance Variables: Family Room Items

Instance variables belong to an object—like items in the family room that everyone in YOUR house can use. Each house (object) has its own copy!

public class Dog {
    String name;    // Instance variable
    int age;        // Instance variable

    public void bark() {
        System.out.println(name + " says Woof!");
    }
}

🔑 Key Rules:

  • Declared inside a class, but outside methods
  • Each object gets its own copy
  • Born when object is created
  • Die when object is destroyed
  • Get default values if you don’t set them

📦 Default Values:

Type Default
int 0
boolean false
String null

🌟 Real Example:

public class Pet {
    String name;     // Instance variable
    int energy = 100; // Can set default

    public void play() {
        energy = energy - 10;
        System.out.println(name + " played!");
    }
}

// Usage:
Pet cat = new Pet();
cat.name = "Whiskers";
cat.play(); // Uses cat's own name!

🌍 Static Variables: The Neighborhood Park

Static variables belong to the CLASS, not any single object—like a park that EVERYONE in the neighborhood shares. Change it once, everyone sees the change!

public class Student {
    static String schoolName = "Sunny School";
    String name; // Instance (each student has own)
}

🔑 Key Rules:

  • Use the static keyword
  • One copy shared by ALL objects
  • Accessed using class name
  • Exists even without creating objects
graph TD A[Static Variable: schoolName] --> B[Student 1] A --> C[Student 2] A --> D[Student 3] style A fill:#FFD700

🌟 Real Example:

public class BankAccount {
    static double interestRate = 0.05;
    double balance; // Each account has own

    public void showRate() {
        // Access with class name!
        System.out.println(BankAccount.interestRate);
    }
}

🔒 Constants with final: The Stone Tablet

Constants are values that NEVER change—like rules carved in stone! Use the final keyword to make a variable unchangeable.

final int MAX_SPEED = 100;
final String GAME_NAME = "Adventure Quest";

🔑 Key Rules:

  • Use final keyword
  • MUST be initialized when declared
  • Cannot be changed after setting
  • Use ALL_CAPS names (convention)

⚠️ Try to Change? ERROR!

final int LIVES = 3;
LIVES = 5; // COMPILATION ERROR!

🌟 Static Constants (Best Practice):

public class Game {
    static final int MAX_PLAYERS = 4;
    static final double PI = 3.14159;

    // Shared AND unchangeable!
}

🎁 The var Keyword: Smart Guessing

Java 10+ gave us var—let Java GUESS the type based on what you assign! It’s like a smart label maker.

var message = "Hello";  // Java knows it's String!
var count = 42;         // Java knows it's int!
var price = 19.99;      // Java knows it's double!

🔑 Key Rules:

  • Only for LOCAL variables
  • Must initialize immediately
  • Type is locked after assignment
  • Cannot use for fields or parameters

✅ Works Great:

var names = new ArrayList<String>();
var reader = new BufferedReader(new FileReader("file.txt"));
// Less typing, still type-safe!

❌ NOT Allowed:

var x;          // ERROR: No value to guess from!
var nothing = null; // ERROR: Can't guess null's type!

🌟 When to Use:

// GOOD: Type is obvious from right side
var list = new ArrayList<String>();
var map = new HashMap<Integer, String>();

// AVOID: Type not clear
var result = process(); // What type is result?

📊 Quick Comparison Table

Variable Type Where Declared Scope Default Value Keyword
Local Inside method Method only None (must set) -
Instance In class, outside methods Object Yes (0, false, null) -
Static In class with static All objects share Yes static
Constant Anywhere Depends on location Must set final

🎮 The Complete Picture

public class GameCharacter {
    // Static: Shared by ALL characters
    static int totalCharacters = 0;
    static final int MAX_LEVEL = 100;

    // Instance: Each character has own
    String name;
    int health = 100;

    public void takeDamage(int damage) {
        // Local: Only exists in this method
        var actualDamage = damage / 2;
        health = health - actualDamage;

        // Using our instance variable
        System.out.println(name + " took damage!");
    }

    public GameCharacter(String playerName) {
        this.name = playerName;
        totalCharacters++; // Update shared count
    }
}

🧠 Remember This Story!

Type Analogy Who Can Access?
Local Toys in YOUR bedroom Only that method
Instance Items in family room Anyone in that object
Static Neighborhood park Everyone (all objects)
final Rules on stone Nobody can change
var Smart label maker Local use, Java guesses type

🚀 You’re Ready!

Now you know the secret of Java’s storage system! Every variable is just a box, and WHERE you put it decides:

  1. Who can see it (scope)
  2. How long it lives (lifetime)
  3. How many copies exist (static vs instance)
  4. Can it change (final or not)

Go build something amazing! 🎯

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.