Saturday, October 26, 2013

Java variables

Variables 

The variable is the basic unit of storage in a java program. it is defined by the combination of an identifier , a type,and an optional initialize. also all variables have a scope,which defines their visibility, and their lifetime, Let us look at variables in depth,

A variable is Temporary memory Allocation   

Declaring Variable

In java all variable must be declared before they can be used, the basic form of a variable declaration is 

TYPE IDENTIFIER = VALUE
The type is one of java's primitive data types, 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, the initialization expression must result in a value of the same type as that specified for the variable,To declare more the one variable of the specified type, use a comma separated list.

        int a ,b,c;
        int d=3,e,f=5;
        byte z = 22;
        double pi = 3.14159;
        char x = 'x';
class Area {

    public static void main(String[] args) {
        double hight,width,area;
        hight = 10.8;
        width = 3.1416;
        area = hight * width;
        System.out.println("Area is :"+ area);
    }
}
Output :
              Area is :33.92928

Dynamic initialization

Although the earlier examples have used only constants as initializers, java allows variable dynamcally, using 
class Area {

    public static void main(String[] args) {
        double high,width;
        high = 10.8;
        width = 3.1416;
        double area = high * width; // area is dynamically initialized 
        System.out.println("Area is :"+ area);
    }
}
Any expression valid at the time the variable is declared, the following program computers the area af a rectangle.
Here,Three Local Variables, high , width, area are declared. the first two high and width are initialized by constants, area is initialized dynamically to the area of the rectangle

No comments:

Post a Comment