Java Variable Definition

Introduction

The variable provides storage in a Java program.

A variable is defined by the combination of

  • an identifier
  • a type
  • an optional initializer

All variables have a scope, which defines their visibility, and a lifetime.

Following is the general form of a variable declaration:

type var-name; 

Here, type specifies the type of variable being declared.

var-name is the name of the variable.

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

Java Variable Declaration

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

Here, type is one of primitive types from Java, or the name of a class or interface.

The identifier is the name of the variable.

You can initialize the variable by specifying an equal sign and a value.

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

Here are several examples of variable declarations of various types.

                                                                                                      
int a, b, c;            // declares three int type variables, a, b, and c.  
int d = 3, e, f = 5;    // declares three more int type variables with initializing  
byte z = 22;            // initializes byte type z.  
double pi = 3.14159;    // declares an approximation of pi.  
char x = 'x';           // the variable x has the value 'x'. 

Dynamic Initialization

Java can initialize variables dynamically via valid expression.

The following program computes the length of the hypotenuse of a right triangle given the lengths of its two opposing sides:

// Demonstrate dynamic initialization.
public class Main{
    public static void main(String args[]) {
      double a = 3.0, b = 4.0;
      /*from   w  w w  . j a va  2  s.  c o  m*/
      // c is dynamically initialized
      double c = Math.sqrt(a * a + b * b);

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

A runnable example

public class Main {
  public static void main(String args[]) {
    int num; // this declares a variable called num

    num = 100; // this assigns num the value 100

    System.out.println("This is num: " + num);

    num = num * 2;//from   w w  w. j av  a2 s. co m

    System.out.print("The value of num * 2 is ");
    System.out.println(num);
  }
}



PreviousNext

Related