Java2all.com  

Variables





Share This Topic -

Variables:

The variable is the basic unit of storage in a Java program. A variable is defined by
the combination of  a type, an identifier and an optional initializer.
 
type is a data type or the name of a class or interface (class and interface will discussed further).for identify the type of variable identifier is a variable name.and optional initializer means users directly initialize the value to the variable if they want.

Declare Variable

Now how we can declare a variable in java?

Syntax for declaring a variable is...

type identifier1=val , identifier2;

Ex.

int a=100, b;  //initialize a and declare b.

byte z = 22;   // initialize z.

double pi = 3.14159;   // declares an approximation of pi.

char x = 'x';   // the variable x has the value 'x'.

Dynamic Initialization

Java allows variables to be initialized dynamically. Take a look following example.
 public class VariableDemo
 {
	public static void main(String[] args)
	{
		int l = 10;
		int b = 20;
		int a;
		
		a = l * b;
		System.out.println("normal initaialization : area is = "+a);
		
		int area = l * b;  // its a dynamic initialization of variable name area
		System.out.println("dynamic initaialization : area is = "+area);
	}
}

Output :
Normal initaialization : area is = 200
Dynamic initaialization : area is = 200

The Scope and Lifetime of Variables

Every variable have scope and life time throughout the program. Here we study when the new scope will be create for how long time (Life time).

A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope.

We use so many variables in our program and declared these variables at the at the start of the main( ) method.

Most other computer languages define two general categories of scopes: global and local. However, these traditional scopes do not fit well with Java’s strict, object oriented model.

Take a look below example.

// Demonstrate variable scope.
class Scope 
{
     public static void main(String args[]) 
     {
           int x;        // known to all code within main
           x = 10;
           if(x == 10)
           { 				  // start new scope
                  int y = 20; 	// known only to this block
                                       // x and y both known here.
                 System.out.println("x and y: " + x + " " + y);
           }
 	   y = x+10;        // Error! y not known here
                                  // x is still known here.
          System.out.println("x is " + x);
     }
}

Here we initialize variable x in main block but the varible y is initialized in if block so scope of variable y is limited to if block.
 
So we will get error on line no. 14 because we are trying to access variable y which is out side of its scope.
 
NOTE: we will study about scope and lifetime in further chapter.