☕ Java

Variables in Java

A variable is just a named box in memory that holds a value. Java is strict about what goes in each box — you tell it the type upfront. Once you get this, the rest of Java clicks into place.

What is a Variable?

A variable is a name you give to a storage location in memory. Instead of working with raw memory addresses (like you'd do in C), you give your data a meaningful name. Real-life analogy: Imagine labeled jars in a kitchen. One jar says "Sugar", another says "Salt". You don't need to remember which shelf or position — you just ask for "Sugar". That's what a variable name does. In Java, you must also specify the type of data the jar can hold — an int jar won't accept text, and a String jar won't accept a decimal number. Syntax: dataType variableName = value;

Three Types of Variables

Java has three kinds of variables, and they differ in where they live and how long they last: 1. Local Variable — Created inside a method. Dies when the method finishes. Only usable within that method. 2. Instance Variable — Belongs to an object. Each object gets its own copy. Created when the object is created, destroyed when the object is garbage collected. 3. Static Variable — Belongs to the class itself, not any individual object. Shared across all instances. Think of it as a class-wide scoreboard.
Java
public class VariableDemo {

    // Instance variable — each Student object gets its own 'name'
    String name = "Alice";

    // Static variable — shared across ALL VariableDemo objects
    static int totalStudents = 0;

    public void showLocal() {
        // Local variable — only alive inside this method
        int age = 25;
        System.out.println("Age: " + age);
        System.out.println("Name: " + name);
    }
}

Variable Naming Rules (and Conventions)

Java has hard rules (break these and it won't compile) and soft conventions (break these and your teammates will hate you). Hard rules: • Must start with a letter, $ or underscore (_) • Cannot start with a digit — 1age is illegal • Cannot use reserved keywords — int, class, new, return, etc. • Case-sensitive — score, Score, and SCORE are three different variables Conventions (follow these): • Use camelCase for variable names: firstName, totalAmount, isLoggedIn • Constants (static final) use ALL_CAPS with underscores: MAX_SPEED, DEFAULT_TIMEOUT • Make names meaningful — x and temp tell you nothing; userEmail and retryCount do