Variables: boxes in memory

Every program needs to remember things: a balance, a name, a count. Java remembers them in variables, named boxes in memory. In this lesson you'll learn how to create, fill and change those boxes, the rules for naming them, how long each box lives, and exactly where in memory Java keeps it.

Module 2 · Language Basics⏱ 16 minBeginnerNo install needed8 practice problems
1 The story

Riya's canteen wallet

The college canteen has started a prepaid wallet. Riya loads ₹500 on Monday. Every chai costs ₹20. She wants a small program that keeps track of her balance, and Arjun Sir uses it to explain the most basic idea in programming.

int balance 500 480 the value can change final int CHAI_PRICE 20 final: locked forever String name → "Riya" holds an arrow to an object myphatshala.in
Riya

Sir, my balance starts at 500, then becomes 480, then 460… How does the program remember the latest number?

Arjun Sir

It stores it in a variable: a box in memory with a label on it. The label is balance. When you buy a chai, Java takes the number out, subtracts 20, and puts the new number back. The old 500 is simply gone.

Riya

And the chai price? That shouldn't change in the middle of the program.

Arjun Sir

Then we lock that box with final. Let's see how Java creates these boxes, and where it keeps them.

2 Definition

What is a variable?

Formal definition (write this in exams)

A variable is a named memory location that stores a value of a specific data type. In Java, every variable must be declared with a type before use (int balance;), may be initialised with a first value (int balance = 500;), and can be assigned new values later unless it is declared final. Based on where they are declared, Java variables are local, instance or static variables.

In simple words

A variable is a labelled box. The label is its name, the type says what kind of thing fits inside (a whole number, a decimal, text…), and the box holds one value at a time. Putting a new value in throws the old one away.

Words you'll meet in this lesson

DeclarationCreating the box: type + name. int balance;
InitialisationPutting the first value in. int balance = 500;
AssignmentReplacing the value later with =. balance = 480;
IdentifierThe name you give a variable, method or class.
ScopeThe part of the code where a variable can be used, usually the { } block it's declared in.
ConstantA final variable whose value can't change after it's set.

Variables at a glance

Syntaxtype name = value; e.g. double price = 19.5;
Several at onceint a = 1, b = 2, c; (works, but one per line is clearer)
Naming rulesLetters, digits, _ and $; can't start with a digit; can't be a keyword; case-sensitive
ConventioncamelCase for variables (chaiCount), UPPER_SNAKE_CASE for constants (CHAI_PRICE)
Constantfinal int CHAI_PRICE = 20;
Type inferencevar count = 3; (Java 10+, local variables only; the type is still fixed as int)
Default valuesFields get defaults (0, 0.0, false, null). Local variables get no default: you must assign before use.

Exam tip: Java is statically typed: a variable's type is fixed at compile time and can never change. int x = 5; x = "five"; is a compile error. Also remember: local variables have no default value, so reading one before assigning it gives the error “variable might not have been initialized”.

3 Types and ways to use it

Three kinds of variables, and where each lives

Java sorts variables by where you declare them. That decides how long they live, who can see them and which part of memory holds them.

Local variable

Declared inside a method or block. Lives in that method's stack frame and disappears when the block ends. No default value.

Stack

Instance variable

Declared in the class, without static. Every object gets its own copy, stored inside the object on the heap. Gets a default value.

Heap (per object)

Static variable

Declared in the class with static. Only one copy, shared by the whole class and every object. Lives as long as the class is loaded.

Class (shared)
LocalInstanceStatic
DeclaredInside a method/blockIn class, no staticIn class, with static
CopiesOne per method callOne per objectOne per class
LifetimeUntil the block endsAs long as the object existsAs long as the class is loaded
Default valueNone, must assign0 / false / null0 / false / null
Exampleint tip = 5;String name; in class Studentstatic int ordersToday;

Ways to write a variable

Declare, then assign

int balance;
balance = 500;
Useful when the value is decided later.

Declare and initialise

int balance = 500;
The most common and safest form.

final constant

final int CHAI_PRICE = 20;
Assigned once, never again.

var (type inference)

var city = "Kharghar";
The compiler infers String. Only for local variables with an initial value.

4 Step by step

The life of one variable

  1. Declare it

    int balance;
    javac reserves a slot for balance in main's stack frame and remembers it holds an int (4 bytes). No value is stored yet, and javac won't let you read it.
  2. Initialise it

    balance = 500;
    The number 500 is written into the slot. In bytecode this is sipush 500 then istore_1.
  3. Read and update it

    balance = balance - 20;
    The right side runs first: read 500, subtract 20, get 480. Then the result is written back into the same slot. The old value 500 is overwritten; it isn't kept anywhere.
  4. Lock a value with final

    final int CHAI_PRICE = 20;
    CHAI_PRICE = 25;   // error: cannot assign a value to final variable CHAI_PRICE
    The check happens at compile time: javac refuses any second assignment. At run time a final local is just a normal slot.
  5. Watch it go out of scope

    {
        int tip = 5;
        balance = balance - tip;
    }
    // tip can't be used here
    A variable exists only inside the { } block where it was declared. After the closing brace the name tip is unknown to javac, and its slot can be reused.
5 See it happen

Boxes appearing, changing and disappearing: both views

Step through Riya's wallet code. Left: the code and output. Right: main's stack frame, slot by slot.

Riya's wallet in memory 6 steps
What you see int balance; balance = 500; balance = balance - 20; final int CHAI_PRICE = 20; { int tip = 5; balance = balance - tip; } CHAI_PRICE = 25; // try to change it System.out.println(balance); A box called balance is created. It is empty. The box gets its first value: 500. Read 500, subtract 20, store 480. A constant, locked at 20. tip exists only inside the { } block. error: cannot assign a value to final variable CHAI_PRICE myphatshala.in
Behind the screen STACK: main() frame 0 · args→ String[0] 1 · balance (int) empty 500 480 475 2 · CHAI_PRICE 🔒20 3 · tip (in block)5 3 · (free, tip is gone) A 4-byte slot is reserved. javac won't letyou read it until a value is assigned. sipush 500 → istore_1 iload_1 · bipush 20 · isub · istore_1500 is overwritten and lost. final is enforced by javac. At run timethis is an ordinary slot. tip lives in slot 3 only inside the block.480 − 5 = 475. Out of scope: slot 3 can be reused.No .class file is made while an error exists. myphatshala.in
6 Real-world use

Variables in real software

Every app you use is full of variables. Here's how the three kinds show up in real systems.

Watch it with an example: a metro card through one day

One variable, balance, holds the card's money. Watch the value in the box change while the name stays the same.

int balance changes, the box stays 6 steps
Animated example int balance = 200; balance = balance - FARE; balance = balance - FARE; balance += 100; // recharge FARE = 50; // not allowed System.out.println(balance); balance int, 4 bytes 200 170 140 240 240 240 FARE final int 30 compile error: cannot assign a value to final variable FARE 200 → 170 → 140 → 240 Console: 240 myphatshala.in
₹480balance

1. Wallets and bank balances

A payment request has local variables like amount, fee and newBalance while it's being processed. The final balance is then saved to a database, because variables vanish when the program stops.

Request→local amount, fee, newBalance→Saved in DB
RiyaKabir

2. Student or customer records

Each Student object has its own instance variables: name, rollNo, marks. A college system may hold thousands of objects, each with its own copy.

new Student()→instance variables per object→Report cards
GST_RATE18

3. Constants for business rules

Rates and limits such as MAX_UPI_LIMIT or GST_RATE are written as named static final constants, so a rule change happens in one place instead of fifty.

static final GST_RATE→used in every bill→One place to update
1,284visitors today

4. Counters and statistics

A static counter can track something for the whole application, like requests served. In multi-user servers this needs care (Module 12), because many threads update the same shared variable.

Each request→static counter + 1 (thread-safe)→Dashboard
DB_URL=…TIMEOUT=30MAX_USERS=500

5. Configuration read into variables

Settings like database URLs and timeouts are read from configuration files or environment variables at start-up and stored in Java variables, so the same code runs in testing and production with different values.

application.properties→String dbUrl, int timeout→Same code, any environment

Examples are simplified to show where variables fit. Real systems differ in detail.

7 Run the code

Riya's wallet program

public class Main {
    static int ordersToday = 0;          // static variable

    public static void main(String[] args) {
        int balance = 500;               // local variable
        final int CHAI = 20;             // constant
        balance = balance - CHAI;
        ordersToday = ordersToday + 1;
        {
            int tip = 5;                 // exists only in this block
            balance = balance - tip;
        }
        System.out.println("Balance: " + balance);
        System.out.println("Orders today: " + ordersToday);
    }
}
Balance: 475 Orders today: 1
  • static int ordersToday = 0;A static variable: one shared copy for the whole class.
  • int balance = 500;A local variable, declared and initialised in one line.
  • final int CHAI = 20;A constant. Any later CHAI = … is a compile error.
  • balance = balance - CHAI;The right side is calculated first (500 − 20), then stored back.
  • { int tip = 5; … }tip lives only inside this block.
8 Line by line

Every variable, step by step

Watch the static variable stay with the class while local variables appear in main's frame, change, and disappear.

Worked examples: real problems, solved and traced in memory

Variables are named boxes on the stack. In these three programs, watch each box appear when it's declared, change when it's assigned, and disappear when its block ends.

Example 1Wallet · payments

A digital wallet's balance through the day

Problem statement

A student's wallet starts with Rs 500. She pays Rs 120 for lunch, gets Rs 200 cashback, then pays Rs 45 for a bus ticket. Track the balance in one variable and print it after each step.

Input
start 500; −120, +200, −45
Expected output
After lunch: Rs 380
After cashback: Rs 580
After bus ticket: Rs 535

Approach

  1. Declare balance once with the starting amount.
  2. Reassign it after each transaction.
  3. Print the running balance.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 2Retail · constants

A GST rate that must never change by accident

Problem statement

A billing program uses the 18% GST rate in several places. Store it in a final variable so nobody can change it by mistake, and compute the GST on two bills.

Input
bills 1200 and 350
Expected output
GST on bill 1: Rs 216.0
GST on bill 2: Rs 63.0

Approach

  1. final double GST = 0.18;: assigned once, then locked.
  2. Use it in two calculations.
  3. Any later GST = ... would be a compile error.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 3Logistics · swap

Swap two delivery slots

Problem statement

A delivery app shows two slots, 10 AM and 4 PM. The customer wants them swapped. Swap the values of two variables using a temporary variable inside a block, and show that temp disappears after the block.

Input
first = 10, second = 16
Expected output
First slot: 16:00
Second slot: 10:00

Approach

  1. Copy the first value into temp.
  2. Copy second into first, then temp into second.
  3. temp is declared inside { }, so it exists only there.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

9 Quiz and revision

Check yourself

Quick revision

Lesson 2.1 in one screen

  • Variable = named memory location with a type. Declare → initialise → assign.
  • Names: letters, digits, _, $; no digit first; no keywords; case-sensitive. camelCase for variables, UPPER_SNAKE_CASE for constants.
  • Local (stack, no default), instance (heap, per object, default), static (class, one shared copy, default).
  • final = assign once (checked at compile time). var = inferred type for locals, still fixed.
  • Scope = the { } block where it's declared.
  • Assignment copies the value; the old value is overwritten.

Interview and viva questions

What is the difference between local, instance and static variables?

Local variables are declared inside methods, live on the stack only during that call and have no default value. Instance variables are declared in the class without static; each object has its own copy on the heap with a default value. Static variables are declared with static; one copy is shared by the whole class.

Why don't local variables get default values?

To catch mistakes. A local variable that's read before being set is almost always a bug, so javac forces you to assign it. Fields get defaults because objects are created in many ways and the JVM must zero their memory anyway.

Is var in Java the same as var in JavaScript?

No. Java's var only asks the compiler to infer the type from the initial value; the variable is still statically typed and can't change type. It works only for local variables with an initializer, not for fields or parameters.

What is a compile-time constant?

A final variable of a primitive type or String, initialised with a constant expression, such as final int CHAI = 20;. javac substitutes its value wherever it's used.

Can two variables have the same name?

Not in the same scope. A local variable can have the same name as a field, which then “shadows” the field inside that method; you reach the field with this.name or ClassName.name.

Practice problems

Declare, assign and update variables, and use final for values that must not change. Every output is fixed. The last three are business tasks.

P1Easy

Declare and print

Store your age (19) and city (Nagpur) in variables and print them.

Input
19, Nagpur
Expected output
19 years, from Nagpur
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int age = 19;
        String city = "Nagpur";
        System.out.println(age + " years, from " + city);
    }
}
19 years, from Nagpur

How it works: each variable has a type, a name and a value.

P2Easy

Update a score

A quiz score starts at 0. Add 10 three times and print it.

Input
(none)
Expected output
Score: 30
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int score = 0;
        score = score + 10;
        score = score + 10;
        score = score + 10;
        System.out.println("Score: " + score);
    }
}
Score: 30

How it works: a variable can be reassigned as often as you like (unless it's final).

P3Easy

Use a constant

Declare final int DAYS_IN_WEEK = 7; and print the number of days in 6 weeks.

Input
6 weeks
Expected output
42
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        final int DAYS_IN_WEEK = 7;
        System.out.println(6 * DAYS_IN_WEEK);
    }
}
42

How it works: constants make code self-explaining: 6 * DAYS_IN_WEEK reads better than 6 * 7.

P4Medium

Swap without temp (arithmetic)

Swap a = 5 and b = 9 using only + and −.

Input
5, 9
Expected output
a = 9, b = 5
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int a = 5, b = 9;
        a = a + b;
        b = a - b;
        a = a - b;
        System.out.println("a = " + a + ", b = " + b);
    }
}
a = 9, b = 5

How it works: a becomes 14, then b = 14 − 9 = 5, then a = 14 − 5 = 9. A temp variable is clearer in real code.

P5Medium

Scope of a block

Declare total outside a block and tip inside it; add the tip to the total inside the block and print total afterwards.

Input
total 400, tip 40
Expected output
Total with tip: 440
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int total = 400;
        {
            int tip = 40;
            total = total + tip;
        }
        System.out.println("Total with tip: " + total);
    }
}
Total with tip: 440

How it works: code inside a block can use variables from outside it; variables declared inside vanish when it ends.

P6Business problem

Stock after sales

A shop has 50 units. It sells 12, receives 30, sells 25. Print the stock after each step.

Input
50; −12, +30, −25
Expected output
After sale: 38
After delivery: 68
After sale: 43
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int stock = 50;
        stock = stock - 12;
        System.out.println("After sale: " + stock);
        stock = stock + 30;
        System.out.println("After delivery: " + stock);
        stock = stock - 25;
        System.out.println("After sale: " + stock);
    }
}
After sale: 38 After delivery: 68 After sale: 43

How it works: one variable tracks a running value, the basis of inventory systems.

P7Business problem

Discount with a constant

A store gives a fixed 15% member discount. Print the price after discount for items costing Rs 2,000 and Rs 640.

Input
2000, 640
Expected output
Rs 1700.0
Rs 544.0
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        final double MEMBER_DISCOUNT = 0.15;
        System.out.println("Rs " + 2000 * (1 - MEMBER_DISCOUNT));
        System.out.println("Rs " + 640 * (1 - MEMBER_DISCOUNT));
    }
}
Rs 1700.0 Rs 544.0

How it works: changing the discount later needs one edit.

P8Business problem

Monthly savings

Salary Rs 32,000; rent Rs 9,500; food Rs 6,000; travel Rs 2,500. Print savings.

Input
as given
Expected output
Savings: Rs 14000
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int salary = 32000;
        int rent = 9500, food = 6000, travel = 2500;
        int savings = salary - rent - food - travel;
        System.out.println("Savings: Rs " + savings);
    }
}
Savings: Rs 14000

How it works: well-named variables make the calculation read like the sentence it comes from.

Real-world scenario questions (asked in company interviews)

Variable mistakes cause some of the most expensive bugs in production. Decide your answer first, then open the model answer.

E-commerce · production incident1–3 years

Customers seeing each other's cart

In a web service, a developer stored the current customer's cart in a static List<Item> cart field “to make it easy to access from every method”. In testing, with one user, it worked. In production, customers started seeing items added by other customers. Why?

The interviewer is checking: do you understand that a static variable is one shared copy for everyone?

Show a strong answer

A static field has exactly one copy for the whole application. A web server handles many customers at the same time on different threads, and all of them read and write that same list. So one customer's items appear in another's cart. It's also a privacy problem.

  • Per-customer data must not be static. Keep it in a local variable or an object created per request or per session, or in the database.
  • Use static only for truly shared things such as constants or carefully designed, thread-safe shared resources.
  • Add a test that simulates two users at once.

Avoid saying: “Add synchronized.” That only stops corruption; everyone would still share one cart.

Retail billing · code reviewFresher

The number 18 appears 40 times

You're reviewing a billing module where the GST rate 18 is typed directly into 40 different calculations. The government changes the rate for one product category, and the team must update the code tonight. What would you suggest, now and for the future?

The interviewer is checking: do you know why “magic numbers” are risky, and how named constants or configuration help?

Show a strong answer
  • Replace the literal with a named constant, for example static final int STANDARD_GST_RATE = 18;, so the meaning is clear and the value lives in one place.
  • Because rates differ by category and change over time, they really belong in configuration or a database table, not in code at all.
  • Search carefully: not every 18 in the code is a GST rate (it might be an age limit). That's exactly why bare numbers are dangerous.
  • Add tests for bill totals so the change can be verified quickly.

Avoid: a blind find-and-replace of “18” across the project.

Fintech · bug fixFresher

The discount that disappeared

A method calculates a final price. Inside an if block for festival offers, someone wrote int price = basePrice - discount;, and after the block the method returns price, which still holds the undiscounted value. There's no error. What's happening?

The interviewer is checking: do you understand scope and how declaring a variable a second time creates a new box?

Show a strong answer

The method already had a variable price. Writing int price = … inside the block declares a new variable rather than updating the existing one. (In Java, a local inside a nested block can't reuse the name of another local in the same method, so the outer one is most likely a field. The new local shadows it.) The discounted value lives in the inner box and disappears at the closing brace.

  • Fix: assign instead of declaring: price = basePrice - discount;
  • Prefer clear names and small methods, and turn on IDE warnings for shadowed variables.
  • Add a unit test for the festival case.

Avoid: adding print statements randomly without first checking where each variable is declared.

Any company · code reviewFresher

“What does d mean?”

Your code has variables named d, temp2, flag and x1. It works, but the reviewer leaves comments on each one asking what they mean. A friend says reviewers are being fussy. How do you respond?

The interviewer is checking: do you value readable code, and can you accept review feedback professionally?

Show a strong answer

The reviewer is right. Code is read many more times than it's written, often by someone else months later.

  • Rename to say what the value is: daysSinceLastLogin, retryCount, isPaymentVerified.
  • Booleans read best as questions: isActive, hasDiscount.
  • Use the IDE's Rename refactoring so every usage updates safely.
  • Reply to the review with thanks and push the update. Good naming often removes the need for comments.

Avoid saying: “It works, so names don't matter.”