The 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] ...] ;

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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.