00:00

Variables in Java – Types, Scope and Examples

A variable is a named place in memory that stores a value your program can read and change. In Java, every variable has a name, a type that decides what it can hold, and a scope that decides where it can be used.

This tutorial covers declaring and initialising variables, the three kinds of variables (local, instance and static), scope, final constants, and the naming rules every Java programmer follows.

1. What Is a Variable?

Think of a variable as a labelled box. The label is the name (price), the box's shape is the type (double), and what is inside is the value (49.5). You can look inside the box or replace its contents, but you cannot put a value of the wrong shape into it.

Syntax
type name;              // declaration
type name = value;      // declaration with initialisation

int age = 30;
String city = "Pune";
boolean isMember = true;

2. Declaring, Initialising and Updating

VariableBasics.java
public class VariableBasics {
    public static void main(String[] args) {
        int quantity;                 // declaration
        quantity = 3;                 // initialisation (first assignment)
        double price = 49.5;          // declaration + initialisation
        String item = "notebook";

        double total = quantity * price;
        System.out.println(quantity + " x " + item + " = " + total);

        quantity = quantity + 2;      // reassignment
        quantity += 1;                // shorthand for quantity = quantity + 1
        System.out.println("New quantity: " + quantity);

        int a = 1, b = 2, c = 3;      // several variables of the same type
        System.out.println("a + b + c = " + (a + b + c));
    }
}
Output
3 x notebook = 148.5
New quantity: 6
a + b + c = 6
  • Declaration introduces the variable and its type.
  • Initialisation gives it its first value. A local variable must be initialised before it is read, or the code will not compile.
  • Assignment with = replaces the current value; compound operators such as += update it.

3. Kinds of Variables

Types of variables in Java: local, instance and static
KindDeclaredExistsCopiesDefault value
Local variableInside a method, constructor or blockWhile that code runsOne per callNone; must be assigned
ParameterIn a method or constructor signatureWhile the method runsOne per callSet by the caller
Instance variable (field)Inside a class, without staticAs long as the object existsOne per objectYes (0, false, null)
Static variable (class variable)Inside a class, with staticAs long as the class is loadedOne per classYes

This example uses all of them. Changing the static school affects every student, while each student keeps its own name and marks:

VariableKinds.java
public class VariableKinds {
    static String school = "Green Valley";   // static (class) variable: one copy for the class
    String name;                             // instance variable: one copy per object
    int marks;

    VariableKinds(String name, int marks) {  // name and marks here are parameters
        this.name = name;
        this.marks = marks;
    }

    String result() {
        String grade = marks >= 60 ? "Pass" : "Fail";   // local variable: lives only in this method
        return name + " (" + school + "): " + grade;
    }

    public static void main(String[] args) {
        VariableKinds s1 = new VariableKinds("Asha", 82);
        VariableKinds s2 = new VariableKinds("Ravi", 45);
        System.out.println(s1.result());
        System.out.println(s2.result());

        VariableKinds.school = "Blue Hills";              // changes it for every object
        System.out.println(s1.result());
        System.out.println(s2.result());
    }
}
Output
Asha (Green Valley): Pass
Ravi (Green Valley): Fail
Asha (Blue Hills): Pass
Ravi (Blue Hills): Fail

4. Variable Scope

The scope of a variable is the part of the code where it can be used. In Java, a local variable is visible from its declaration to the end of the enclosing block { }.

ScopeDemo.java
public class ScopeDemo {
    int count = 100;                         // field

    void show(int count) {                   // parameter shadows the field
        System.out.println("parameter count = " + count);
        System.out.println("field count     = " + this.count);
    }

    public static void main(String[] args) {
        int total = 0;                       // visible in the whole main method
        for (int i = 1; i <= 3; i++) {       // i exists only inside the loop
            int square = i * i;              // square exists only inside one iteration
            total += square;
        }
        // System.out.println(i);           // compile error: cannot find symbol i
        System.out.println("total = " + total);

        {
            int temp = 5;                    // block scope
            System.out.println("temp = " + temp);
        }

        new ScopeDemo().show(7);
    }
}
Output
total = 14
temp = 5
parameter count = 7
field count     = 100
  • The loop variable i and square exist only inside the loop.
  • A block { } creates its own scope.
  • A parameter or local variable with the same name as a field shadows the field; use this.count to reach the field.
  • Two local variables in overlapping scopes cannot share a name.

5. Final Variables and Constants

A variable declared final can be assigned only once. For object references, final fixes the reference, not the object's contents. A static final field with a fixed value is a constant.

FinalVariables.java
import java.util.ArrayList;
import java.util.List;

public class FinalVariables {
    static final double GST_RATE = 0.18;     // a constant: UPPER_SNAKE_CASE

    public static void main(String[] args) {
        final int maxUsers = 50;
        // maxUsers = 60;                    // compile error: cannot assign a value to final variable

        final List<String> names = new ArrayList<>();
        names.add("Asha");                   // allowed: the object can change
        names.add("Ravi");
        // names = new ArrayList<>();        // not allowed: the reference cannot change

        System.out.println("Limit " + maxUsers + ", names " + names);
        System.out.println("GST on 1000 = " + 1000 * GST_RATE);
    }
}
Output
Limit 50, names [Asha, Ravi]
GST on 1000 = 180.0

Learn more in final keyword in Java.

6. Naming Rules and Conventions

Rules (enforced by the compiler)

  • Names can contain letters, digits, _ and $.
  • They must not start with a digit.
  • They must not be a reserved keyword such as class, int or new.
  • They are case-sensitive: total and Total are different variables.
  • A single underscore _ on its own is not a valid name; since Java 22 it marks an unnamed variable.

Conventions (followed by everyone)

WhatStyleExamples
Variables and parameterscamelCasefirstName, totalAmount, isActive
ConstantsUPPER_SNAKE_CASEMAX_SIZE, GST_RATE
BooleansRead as yes/no questionsisValid, hasMore, canEdit

Choose descriptive names (orderCount) over short ones (oc), except for tiny scopes such as loop counters (i).

7. Using var for Local Variables

Since Java 10, you can write var instead of the type for local variables that have an initial value. The compiler infers the type:

var examples
var count = 10;                          // int
var message = "Hello";                   // String
var prices = new ArrayList<Double>();    // ArrayList<Double>

// var x;                                // error: cannot infer type without an initializer
// var y = null;                         // error: cannot infer type from null

Use var when the type is obvious from the right-hand side; write the type explicitly when it helps readers.

8. Where Variables Live in Memory

  • Local variables and parameters live in the method's stack frame and disappear when the method returns.
  • Instance variables live inside their object on the heap.
  • Static variables are stored with the class data and live as long as the class is loaded.

For reference types, the variable stores a reference; the object itself is always on the heap.

9. Common Mistakes

  • Using a local variable before assigning it: variable might not have been initialized.
  • Using a variable outside its block: cannot find symbol.
  • Accidentally shadowing a field with a parameter and forgetting this. in a constructor.
  • Making a variable static when each object needs its own value.
  • Assuming final makes an object immutable.

10. Summary

  • A variable has a type, a name, a value and a scope.
  • Local variables live inside methods and must be initialised; fields get default values.
  • Instance variables belong to each object; static variables are shared by the class.
  • final variables can be assigned once; static final values are constants.
  • Follow camelCase for variables and UPPER_SNAKE_CASE for constants.

Related Tutorials

Reference: dev.java: Variables