Java Variable

In this chapter you will learn:

  1. How to declaring a variable
  2. How to use Assignment Operator
  3. How to initialize a variable dynamically

Declaring a Variable

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

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

There are three parts in variable definition:

  • 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'.
  }/*w ww.ja v a 2  s.c o  m*/
}

Variable cannot be used prior to its declaration.


public class Main {
  public static void main(String[] argv) {
//ww  w.  j  a va  2 s .c o m
    count = 100; // Cannot use count before it is declared! 
    int count;
  }
}

Compiling the code above generates the following error message:

Assignment Operator

The assignment operator is the single equal sign, =. It has this general form:


var = expression;

type of var must be compatible with the type of expression. The assignment operator allows you to create a chain of assignments.

 
public class Main {
  public static void main(String[] argv) {
    int x, y, z;//w  w w .j  a v a2  s  .c om
    x = y = z = 100; // set x, y, and z to 100
    System.out.println("x is " + x);
    System.out.println("y is " + y);
    System.out.println("z is " + z);
  }
}

The output:

Dynamic Initialization

Java allows variables to be initialized dynamically. In the following code the Math.sqrt returns the square root of 2 * 2 and assigns the result to c directly.


public class Main {
  public static void main(String args[]) {
/*from w w w.ja v a  2  s. c  o m*/
    // c is dynamically initialized
    double c = Math.sqrt(2 * 2);

    System.out.println("c is " + c);
  }
}

The output from the code above is

Next chapter...

What you will learn in the next chapter:

  1. What are the eight primitive types in Java
  2. What are integer types in Java
  3. Java floating point types
Home »
  Java Tutorial »
    Java Langauge »
      Java Hello World
Your first Java program
Your second Java program
Java Keywords and Identifiers
Java Variable