Tuesday, 26 May 2009

Variables

Here we would be talking about variables

Every programming language has variables. A variable can be defined

as a named storage location whose value can change during the

execution of program .

General declaration syntax is :

data type variable name = [initialization value]

eg int number ; // declaration without initialization

int number = 10 ; // declaration with initialization

  • Initialization is optional
  • Once declared other parts of program (code) can refer to it by it's name

Scope and Lifetime of a variable

Scope means which part of program can access a previously defined variable.

Normally, scope is defined by curly braces. We will explain scope rules with the help

of following examples.

Consider a for loop and a function

for ( int count = 0 ; count <>{

int i = 5 ;

System.out.println ("Value of i is : " + i ) ; // prints on console

}

void other ( )

{

System.out.println ("Value of i is : " + i ) ; // results in compile time error

}

As variable i is defined inside the for loop, enclosed in the braces it can be used

only there.Trying to use it anywhere else would result in compile time error

Variables declared inside ( ) can also be accessed within the following braces.

In the for loop above, variable count has been declared inside the ( ) and can be

accessed only inside the for loop .

Nested scopes



It is possible to embed another block defined by { } inside another block

Lets look at an example on how scope rule works when there are nested scopes

for ( int i = 0 ; i <>

{ // start outer

// j is not visible (accessible here)

for ( int j = 0 ; j <>

{ // start inner

// i is accessible here

} // end inner

} // end outer

Lifetime : As soon as a variable goes out of scope, it's value is destroyed because it can not

be used after it goes out of scope

for ( int i = 0 ; i <>

{

int x = 10 ;

x = x * 5 ;

System.out.println (" Value of x is : " + x) ;

}

Output is :

Value of x is : 50

Value of x is : 50

Value of x is : 50

This is because every time, next iteration of for loop occurs x goes

out of scope ( as code execution moves out of { } ) . So it's value gets destroyed.

It again gets initialized to 10 when the loop is entered .

Next we will be discussing about Arrays