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.
Sir, my balance starts at 500, then becomes 480, then 460… How does the program remember the latest number?
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.
And the chai price? That shouldn't change in the middle of the program.
Then we lock that box with final. Let's see how Java creates these boxes, and where it keeps them.
What is a variable?
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.
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
int balance;int balance = 500;=. balance = 480;{ } block it's declared in.final variable whose value can't change after it's set.Variables at a glance
| Syntax | type name = value; e.g. double price = 19.5; |
|---|---|
| Several at once | int a = 1, b = 2, c; (works, but one per line is clearer) |
| Naming rules | Letters, digits, _ and $; can't start with a digit; can't be a keyword; case-sensitive |
| Convention | camelCase for variables (chaiCount), UPPER_SNAKE_CASE for constants (CHAI_PRICE) |
| Constant | final int CHAI_PRICE = 20; |
| Type inference | var count = 3; (Java 10+, local variables only; the type is still fixed as int) |
| Default values | Fields 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”.
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.
StackInstance 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)| Local | Instance | Static | |
|---|---|---|---|
| Declared | Inside a method/block | In class, no static | In class, with static |
| Copies | One per method call | One per object | One per class |
| Lifetime | Until the block ends | As long as the object exists | As long as the class is loaded |
| Default value | None, must assign | 0 / false / null | 0 / false / null |
| Example | int tip = 5; | String name; in class Student | static 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.
The life of one variable
Declare it
javac reserves a slot forint balance;balancein main's stack frame and remembers it holds anint(4 bytes). No value is stored yet, and javac won't let you read it.Initialise it
The number 500 is written into the slot. In bytecode this isbalance = 500;sipush 500thenistore_1.Read and update it
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.balance = balance - 20;Lock a value with final
The check happens at compile time: javac refuses any second assignment. At run time a final local is just a normal slot.final int CHAI_PRICE = 20; CHAI_PRICE = 25; // error: cannot assign a value to final variable CHAI_PRICEWatch it go out of scope
A variable exists only inside the{ int tip = 5; balance = balance - tip; } // tip can't be used here{ }block where it was declared. After the closing brace the nametipis unknown to javac, and its slot can be reused.
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.
int balance;declares a variable: a box named balance that can hold one whole number.balance = 500;initialises it with its first value.balance = balance - 20;reads the current value, calculates 480 and stores it back.final int CHAI_PRICE = 20;creates a constant.- Inside the
{ }block,tipis created, used, and then goes out of scope. - Trying to change
CHAI_PRICEis rejected by javac: the program doesn't even compile.
- javac gives
balanceslot 1 in main's stack frame: 4 bytes for anint. No value yet. - 500 is stored in slot 1 (bytecode
sipush 500,istore_1). - The JVM loads 500, pushes 20, subtracts, and stores 480 in the same slot. The old value is gone.
CHAI_PRICEgets slot 2. The lock is a compile-time rule; at run time it's a normal slot.tiptakes slot 3 only while the block runs. The balance becomes 475.- After the block, slot 3 is free. The attempt to reassign the final variable stops compilation.
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.
- Declare:
int balance = 200;reserves a 4-byte box namedbalanceand puts 200 in it. The fare is a constant,final int FARE = 30; - Morning trip: the right side is worked out first (200 − 30), then the result 170 replaces the old value. The old 200 is gone.
- Evening trip: same line, new value: 140. A variable remembers only its latest value.
- Recharge:
balance += 100is short forbalance = balance + 100. Now 240. - Constant: trying to change
FAREfails at compile time, because it isfinal. Business rules like fares and tax rates are often constants. - Print: the program reads the box and prints 240. Same name all day; the value moved 200 → 170 → 140 → 240.
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.
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.
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.
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.
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.
Examples are simplified to show where variables fit. Real systems differ in detail.
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);
}
}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 laterCHAI = …is a compile error.balance = balance - CHAI;The right side is calculated first (500 − 20), then stored back.{ int tip = 5; … }tiplives only inside this block.
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.
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.
start 500; −120, +200, −45
After lunch: Rs 380 After cashback: Rs 580 After bus ticket: Rs 535
Approach
- Declare
balanceonce with the starting amount. - Reassign it after each transaction.
- 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.
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.
bills 1200 and 350
GST on bill 1: Rs 216.0 GST on bill 2: Rs 63.0
Approach
final double GST = 0.18;: assigned once, then locked.- Use it in two calculations.
- 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.
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.
first = 10, second = 16
First slot: 16:00 Second slot: 10:00
Approach
- Copy the first value into
temp. - Copy second into first, then temp into second.
tempis 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.
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.
Declare and print
Store your age (19) and city (Nagpur) in variables and print them.
19, Nagpur
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);
}
}How it works: each variable has a type, a name and a value.
Update a score
A quiz score starts at 0. Add 10 three times and print it.
(none)
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);
}
}How it works: a variable can be reassigned as often as you like (unless it's final).
Use a constant
Declare final int DAYS_IN_WEEK = 7; and print the number of days in 6 weeks.
6 weeks
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);
}
}How it works: constants make code self-explaining: 6 * DAYS_IN_WEEK reads better than 6 * 7.
Swap without temp (arithmetic)
Swap a = 5 and b = 9 using only + and −.
5, 9
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);
}
}How it works: a becomes 14, then b = 14 − 9 = 5, then a = 14 − 5 = 9. A temp variable is clearer in real code.
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.
total 400, tip 40
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);
}
}How it works: code inside a block can use variables from outside it; variables declared inside vanish when it ends.
Stock after sales
A shop has 50 units. It sells 12, receives 30, sells 25. Print the stock after each step.
50; −12, +30, −25
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);
}
}How it works: one variable tracks a running value, the basis of inventory systems.
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.
2000, 640
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));
}
}How it works: changing the discount later needs one edit.
Monthly savings
Salary Rs 32,000; rent Rs 9,500; food Rs 6,000; travel Rs 2,500. Print savings.
as given
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);
}
}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.
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
staticonly 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.
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.
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.
“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.”