Java Variables

Naveen AnamaneniUpdated · 6 min read

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.

Wallet.java▶ Try it
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);
    }
}
Output
Balance: Rs. 500
After chai and samosa: Rs. 380

How it works

  1. Line 3 declares the variable: type int, name balance. Java sets aside room for one whole number.
  2. Line 4 assigns a value with =. Read = as "becomes", not "equals".
  3. 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:

Static, instance and local variables, and where each lives
KindDeclaredHow many copiesLivesDefault value?
LocalInside a method or blockOne per method callUntil the method or block endsNo: you must assign it
InstanceIn the class, without staticOne per objectAs long as its objectYes (0, false, null)
StaticIn the class, with staticOne for the whole classAs long as the class is loadedYes (0, false, null)

All Three in One Program

Coach.java▶ Try it
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);
    }
}
Output
S4 and B2
Coaches: 2
Seats: 144

How it works

  1. Line 2: totalCoaches is static, so there's exactly one, shared by the whole class.
  2. Line 3: code is an instance variable. Lines 6 and 10 create two Coach objects with new, and each gets its own code: one holds "S4", the other "B2".
  3. Lines 8 and 12 add 1 to the single shared counter, so it ends at 2.
  4. Line 14: seatsPerCoach is local to main. It exists only while main runs, 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

  1. 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.
  2. Harder: In Coach, add an instance variable int bookedSeats. Give S4 40 booked seats and B2 55, then print the total booked seats across both coaches.

Quick check: Java variables

4 questions
1Which line declares and initializes a variable?
2How many copies of a static variable exist?
3Which kind of variable has no default value?
4Two Coach objects each set code. How many code values exist?

Key Takeaways

Was this tutorial helpful?

Lesson 31 of 482