JB Header

Variables in Java: Declaration, Initialization and Scope

Introduction Programs work with data - prices, names, counts, dates - and they keep that data in variables. This tutorial explains variables in Java: how to declare and initialize them, and where they can be used. We will start with what a variable is and how to declare one. We will then see how to initialize and change variables, and Java's rule that a local variable must have a value before it is used. Next we will look at the three kinds of variables - local, instance and static - and at scope, which decides where a variable can be used. Lastly, we will make a variable unchangeable with final.

(Note - The naming rules for variables are covered in Java Syntax BasicsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords.) What is a variable? A variable is a named location in memory which holds a value. Every variable in Java has -
  • a type, which decides what kind of values it can hold - such as int for whole numbers, double for decimal numbers, or String for text;
  • a name, which you use to refer to it;
  • and a value, which can usually change while the program runs.
Java is a statically typed language - a variable's type is fixed when it is declared, and the compiler makes sure only values of that type are stored in it. Declaring and initializing variables Syntax of a variable declaration
type name = initialValue;
Where,
  • type is the variable's data type, and name is its name.
  • = initialValue is optional. Giving a variable its first value is called initializing it.
Declaring, initializing and changing variables
//VariablesDemo.java
public class VariablesDemo {
  public static void main(String[] args) {
    int quantity;              // declared, not yet initialized
    quantity = 3;              // initialized later

    double price = 249.50;     // declared and initialized together
    String product = "Java book";
    boolean inStock = true;

    int width = 4, height = 5; // two variables of the same type in one declaration

    System.out.println(quantity + " x " + product + " at " + price + ", in stock: " + inStock);
    System.out.println("Area = " + (width * height));

    quantity = quantity + 2;   // assigning a new value
    System.out.println("New quantity = " + quantity);
  }
}
 OUTPUT of the above code
3 x Java book at 249.5, in stock: true
Area = 20
New quantity = 5
Explanation of the code
  • quantity is declared on one line and initialized on the next. price, product and inStock are declared and initialized in one statement - the most common style.
  • int width = 4, height = 5; declares two int variables at once. It is allowed, but one declaration per line is usually clearer.
  • quantity = quantity + 2; reads the current value (3), adds 2, and stores the result back in quantity. The = sign means assign, not equals.
A local variable must be initialized before use Variables declared inside a method are called local variables. Java does not give local variables a default value, and the compiler refuses to compile code which might read one before it has been assigned -
Using a local variable before initializing it
//Uninitialized.java
public class Uninitialized {
  public static void main(String[] args) {
    int total;
    System.out.println(total);
  }
}
 OUTPUT on compiling the above code
Uninitialized.java:5: error: variable total might not have been initialized
    System.out.println(total);
                       ^
1 error
This rule catches a whole class of bugs at compile time. The compiler also rejects declaring two local variables with the same name in the same scope, and assigning a value of the wrong type - such as a String to an int variable. Local, instance and static variables Where a variable is declared decides what kind of variable it is -
  • Local variables: Declared inside a method or block. They exist only while that method or block runs, and must be initialized before use. Method parameters are local variables too.
  • Instance variables (fields): Declared inside a class, outside any method, without static. Every object of the class gets its own copy.
  • Static variables (class variables): Declared inside a class with static. There is only one copy, shared by all objects of the class.
Unlike local variables, instance and static variables get default values if you do not initialize them - 0 for numbers, false for boolean, and null for objects such as String.
Local, instance and static variables
//Counter.java
public class Counter {
  static int totalCounters = 0;   // static variable - one copy shared by all Counters
  String name;                    // instance variable - each Counter has its own
  int count;                      // instance variable, default value 0

  Counter(String name) {          // name (the parameter) is a local variable
    this.name = name;
    totalCounters = totalCounters + 1;
  }

  void increment() {
    int step = 1;                 // local variable
    count = count + step;
  }

  public static void main(String[] args) {
    Counter visits = new Counter("visits");
    Counter clicks = new Counter("clicks");
    visits.increment();
    visits.increment();
    clicks.increment();
    System.out.println(visits.name + " = " + visits.count);
    System.out.println(clicks.name + " = " + clicks.count);
    System.out.println("Counters created = " + Counter.totalCounters);
  }
}
 OUTPUT of the above code
visits = 2
clicks = 1
Counters created = 2
Explanation of the code
  • Each Counter object has its own name and count, so visits counted to 2 and clicks to 1 independently. count started at its default value, 0.
  • totalCounters is static, so both objects share one copy, and it counted both of them.
  • step exists only while increment() runs. Classes, objects and constructors are covered in detail later in this series - for now, notice where each kind of variable is declared.
Scope - where a variable can be used The scope of a variable is the part of the program where its name can be used. A local variable's scope starts where it is declared and ends at the closing brace of the block it was declared in. Variables declared in an inner block are not visible outside it.
Variable scope in blocks
//ScopeDemo.java
public class ScopeDemo {
  public static void main(String[] args) {
    int outer = 10;                       // visible until the end of main()
    if (outer > 5) {
      int inner = 20;                     // visible only inside this if block
      System.out.println("Inside the block: outer = " + outer + ", inner = " + inner);
    }
    for (int i = 1; i <= 2; i++) {        // i is visible only inside the loop
      System.out.println("Loop: i = " + i);
    }
    System.out.println("After the block: outer = " + outer);
  }
}
 OUTPUT of the above code
Inside the block: outer = 10, inner = 20
Loop: i = 1
Loop: i = 2
After the block: outer = 10
Trying to use inner after its block has ended is a compile error -
Using a variable outside its scope
//OutOfScope.java
public class OutOfScope {
  public static void main(String[] args) {
    if (true) {
      int inner = 20;
    }
    System.out.println(inner);
  }
}
 OUTPUT on compiling the above code
OutOfScope.java:7: error: cannot find symbol
    System.out.println(inner);
                       ^
  symbol:   variable inner
  location: class OutOfScope
1 error
Note - Declare variables in the smallest scope that works, as close as possible to where they are first used. This makes code easier to read, and prevents a variable from being changed by mistake elsewhere. Constants with final Adding final to a declaration makes a variable a constant - it can be assigned only once. A static final field is the usual way to define a named constant, written in capitals by convention.
Assigning to a final variable
//FinalDemo.java
public class FinalDemo {
  static final double TAX_RATE = 0.18;

  public static void main(String[] args) {
    final int maxItems = 10;
    maxItems = 20;
    System.out.println(maxItems * TAX_RATE);
  }
}
 OUTPUT on compiling the above code
FinalDemo.java:7: error: cannot assign a value to final variable maxItems
    maxItems = 20;
    ^
1 error
Named constants such as TAX_RATE make code easier to read than bare numbers, and if the value ever changes, you change it in only one place. Summary In this tutorial we first saw that a variable has a type, a name and a value. We then declared and initialized variables, assigned new values to them, and saw that a local variable must be initialized before it is used. Next we looked at local, instance and static variables, and saw that only instance and static variables get default values. We then learned how scope limits where a variable can be used. Lastly, we made variables into constants with final. In the next tutorial, we will look at Java's primitive data typesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples - the types of values a variable can hold.