Variable stores value in a Java program

A variable is defined by an identifier, a type, and an optional initializer. The variables also have a scope(visibility / lifetime).

Declaring a Variable

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:


type identifier [ = value][, identifier [= value] ...] ;
  • type could be int or float.
  • identifier is the variable's name.
  • Initialization includes an equal sign and a value.

To declare more than one variable of the specified type, use a comma-separated list.


int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.

The following variables are defined and initialized in one expression.


public class Main {
  public static void main(String[] argv) {
    byte z = 2; // initializes z.
    double pi = 3.14; // declares an approximation of pi.
    char x = 'x'; // the variable x has the value 'x'.
  }
}

Variable cannot be used prior to its declaration.


public class Main {
  public static void main(String[] argv) {

    count = 100; // Cannot use count before it is declared! 
    int count;
  }
}

Compiling the code above generates the following error message:


D:\>javac Main.java
Main.java:4: cannot find symbol
symbol  : variable count
location: class Main
    count = 100; // Cannot use count before it is declared!
    ^
1 error
Home 
  Java Book 
    Language Basics  

Variables:
  1. Variable stores value in a Java program
  2. Assignment Operator
  3. Dynamic Initialization
  4. Scope and Lifetime of Variables