Wednesday, 12 October 2011

Variables Type Conversion and Type Casting


The variable is the basic unit of storage in a Java program.

A variable is defined by the combination of an identifier, a type, and an optional initializer.

The value held in the variable can be changed during the execution of program.

A variable is declared by providing the type of the variable as well as an unique identifier that uniquely identifies the variable.

To declare a variable consider following syntax:

                     type var_name;

The type is one of Java’s atomic types, or the name of a class or interface. The var_name is the identifier which specifies the name of the variable. To declare more than one variable of the specified type, use a comma-separated list.

Ex  int x;
 int no1,no2,no3;

Assign value to the variable
Syntax:
            Var_name=value;

Ex  no1=10;
 no2=20;

Dynamic Initialization

        Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
Ex  int no=10;

Scope and lifetime of variable.

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

Java allows variables to be declared within any block. A block defines a scope. Thus, each time when start a new block, a new scope is created , A scope determines what objects are visible to other parts of the program. Blocks are useful in grouping related statements together. A block can be further subdivided into subblock which can be further divided into sub-sub blocks.

Ex,
{                 // outer block
int x;
x = 10;
if(x == 10)
 {              // start new scope
THUAGE
int y = 20; // known only to this block
  // x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
 }
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}

According to the above example any variable declared in the inner block are local to that block and are not visible to the outer block. Variable get destroyed when program  in execution leaves their scope. That is scope also determines the lifetime of those variables.

Another important note need to be taken in consideration is  that the variable must be declared before it use in the program.

Ex, x=10;
      int x;

Here, the given statement is wrong.


Posted By: Ruchita Pandya

No comments:

Post a Comment