Java Variables
A locker at a railway station has a number on the door and something inside it. You find your bag by the number, and you can swap what's inside without changing the number. A variable is the same idea in a program: a named place in memory that holds a value. The name stays fixed; the value can change.
Declare, Assign, Use
Every variable in Java has three things: a type, a name and a value.
public class Wallet {
public static void main(String[] args) {
int balance;
balance = 500;
System.out.println("Balance: Rs. " + balance);
balance = balance - 120;
System.out.println("After chai and samosa: Rs. " + balance);
}
}Balance: Rs. 500
After chai and samosa: Rs. 380How it works
- Line 3 declares the variable: type
int, namebalance. Java sets aside room for one whole number. - Line 4 assigns a value with
=. Read=as "becomes", not "equals". - Line 6 reads the current value, subtracts 120 and stores the result back in the same variable.
You'll usually declare and assign in one line: int balance = 500;. This is called initializing the variable.
Try it yourself: add a line that adds Rs. 1000 to balance (a top-up), then print it.
Three Kinds of Variables
Where you declare a variable decides its kind:
| Kind | Declared | How many copies | Lives | Default value? |
|---|---|---|---|---|
| Local | Inside a method or block | One per method call | Until the method or block ends | No: you must assign it |
| Instance | In the class, without static | One per object | As long as its object | Yes (0, false, null) |
| Static | In the class, with static | One for the whole class | As long as the class is loaded | Yes (0, false, null) |
All Three in One Program
public class Coach {
static int totalCoaches = 0;
String code;
public static void main(String[] args) {
Coach s4 = new Coach();
s4.code = "S4";
totalCoaches++;
Coach b2 = new Coach();
b2.code = "B2";
totalCoaches++;
int seatsPerCoach = 72;
System.out.println(s4.code + " and " + b2.code);
System.out.println("Coaches: " + totalCoaches);
System.out.println("Seats: " + totalCoaches * seatsPerCoach);
}
}S4 and B2
Coaches: 2
Seats: 144How it works
- Line 2:
totalCoachesis static, so there's exactly one, shared by the whole class. - Line 3:
codeis an instance variable. Lines 6 and 10 create twoCoachobjects withnew, and each gets its owncode: one holds"S4", the other"B2". - Lines 8 and 12 add 1 to the single shared counter, so it ends at 2.
- Line 14:
seatsPerCoachis local tomain. It exists only whilemainruns, and no other method can see it.
Objects and new are covered properly in Level 2. For now, notice that instance variables come one per object, and static variables one per class.
Try it yourself: create a third coach, A1, and update the counter. What do the last two lines print now?
Common Mistakes
Declaring the same name twice in one method. int total = 0; followed later by int total = 5; fails with variable total is already defined. Leave out the type the second time: total = 5;.
Expecting each object to have its own static variable. Changing a static variable through one object changes it for all of them, because there's only one.
Using a variable outside its braces. A variable declared inside { } disappears at the closing brace. The next lesson, "Scope and Lifetime of Variables", explains this.
Interview Corner
What are the types of variables in Java?
Three: local variables, declared inside a method or block and living only while it runs; instance variables, declared in a class without static, with one copy per object; and static (class) variables, declared with static, with one copy shared by the whole class.
Do local variables get default values?
No. A local variable must be assigned before it's read, or the code doesn't compile. Instance and static variables get default values: 0 for numbers, false for boolean, '\u0000' for char and null for references.
Where are local, instance and static variables stored?
Local variables live in the method's frame on the stack. Instance variables live inside their object on the heap. Static variables are stored with the class data, in the method area (Metaspace in HotSpot).
Practice
- Easy: Declare variables for a train's name, its number of coaches and whether it has a pantry car. Print a sentence using all three.
- Harder: In
Coach, add an instance variableint bookedSeats. Give S4 40 booked seats and B2 55, then print the total booked seats across both coaches.
Key Takeaways
Was this tutorial helpful?