Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

Java Variables

A variable is a named memory location that holds a value which can change during program execution. In Java, every variable must be declared with a type before it is used, because Java is a statically and strongly typed language.

Why it matters

Where a variable is declared decides how long it lives, who can see it, and whether it is shared. Bugs such as "every object seems to have the same value" or "variable might not have been initialized" are not random — they follow directly from the difference between local, instance and static variables.

Watch: How Java Variables Control Your Data

A quick video on how Java variables store and control your program's data.

Watch on YouTube

Types of Variables in Java

Java classifies variables based on where they are declared and how long they live.

  • Local variables — declared inside a method, constructor, or block. They exist only during that call and must be initialized before use; Java gives them no default value.
  • Instance variables — declared inside a class but outside any method, without the static keyword. Each object gets its own copy, and they receive default values (0, false, null) if not explicitly initialized.
  • Static (class) variables — declared with the static keyword. They belong to the class itself, are shared by all instances, and are initialized once when the class is loaded.

Declaration and Initialization

Declaration reserves a name and type (int age;). Initialization assigns a value (age = 25;). You can combine both in one statement: int age = 25;. Variable names in Java must start with a letter, underscore, or dollar sign, cannot be a reserved keyword, and are case-sensitive.

Example

Local, instance, and static variables together

Java
public class VariableDemo {

    int instanceCount;              // instance variable, default value 0
    static int totalObjects = 0;    // static variable, shared across all objects

    VariableDemo() {
        instanceCount = 1;
        totalObjects++;
    }

    void showLocalVariable() {
        int localValue = 10;        // local variable, must be initialized before use
        System.out.println("Local value: " + localValue);
    }

    public static void main(String[] args) {
        VariableDemo obj1 = new VariableDemo();
        VariableDemo obj2 = new VariableDemo();
        obj1.showLocalVariable();
        System.out.println("Total objects created: " + VariableDemo.totalObjects);
    }
}
Output
Local value: 10
Total objects created: 2

Common Mistakes

  • Using a local variable before assigning it a value — this is a compile-time error in Java, unlike some other languages.
  • Expecting instance variables to be shared across objects — each object has its own independent copy unless the variable is static.
  • Shadowing an instance variable with a local variable of the same name and forgetting to use "this.fieldName" to refer to the instance version.

Exercise

Model bank accounts that each keep their own balance while the class keeps one shared count of how many accounts exist. Fill in the two field declarations and the constructor.

Expected output: Asha: 500, Ravi: 1200, then Accounts opened: 2, each on its own line.

Java · starter code
public class BankAccount {
    // TODO: declare an instance variable for the owner name and one for the balance
    // TODO: declare a static variable that counts accounts

    BankAccount(String owner, int balance) {
        // TODO: store the values and increase the shared counter
    }

    public static void main(String[] args) {
        BankAccount first = new BankAccount("Asha", 500);
        BankAccount second = new BankAccount("Ravi", 1200);

        System.out.println(first.owner + ": " + first.balance);
        System.out.println(second.owner + ": " + second.balance);
        System.out.println("Accounts opened: " + BankAccount.accountCount);
    }
}
Show hints
  • Use this.owner = owner; to tell the field apart from the parameter with the same name.
  • Only the counter should be static; a static balance would be shared by every account.
Show solution
Java · solution
public class BankAccount {
    String owner;
    int balance;
    static int accountCount = 0;

    BankAccount(String owner, int balance) {
        this.owner = owner;
        this.balance = balance;
        accountCount++;
    }

    public static void main(String[] args) {
        BankAccount first = new BankAccount("Asha", 500);
        BankAccount second = new BankAccount("Ravi", 1200);

        System.out.println(first.owner + ": " + first.balance);
        System.out.println(second.owner + ": " + second.balance);
        System.out.println("Accounts opened: " + BankAccount.accountCount);
    }
}

Quick quiz

1. What happens if you read a local variable before assigning it a value?

  • A. It contains 0
  • B. It contains null
  • C. It throws an exception at runtime
  • D. The code does not compile
Show answer

D. Local variables have no default value. The compiler rejects any read that is not definitely preceded by an assignment.

2. What is the default value of an int instance variable that is never assigned?

  • A. 0
  • B. null
  • C. -1
  • D. It has no default
Show answer

A. Instance and static variables get defaults: 0 for numeric types, false for boolean, and null for references.

3. A class has one static variable. You create three objects of that class. How many copies of the variable exist?

  • A. Three
  • B. Four
  • C. One
  • D. None until it is assigned
Show answer

C. A static variable belongs to the class, so there is exactly one copy shared by all objects.

Interview questions

What is the difference between an instance variable and a static variable?

Show answer

An instance variable belongs to an object: each object has its own copy, created when the object is created. A static variable belongs to the class: there is one copy, created when the class is loaded and shared by every object.

Use instance variables for state that differs per object (a balance) and static variables for state that is genuinely class-wide (a counter or a constant).

Why do local variables not get default values when fields do?

Show answer

It is a deliberate language rule to catch bugs. A field can be read from many methods at any time, so the language guarantees it a known starting value. A local variable lives only inside one method, so the compiler can check every path and insist that you assign it before reading it — reading an unassigned local is almost always a mistake.

Key Points to Remember

  • Three kinds of variables: local, instance, and static (class) variables.
  • Local variables have no default value and must be initialized before use.
  • Instance variables belong to each object; static variables are shared across all objects of the class.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering