Sunday 3 July 2016

Variable in Java

Variable
Variable is name of reserved area allocated in memory.

Syntax of Declaration of Variable:-

Data_type var_name1,var_name2,…. ;

The Data_type is one of the java’s data type and var_name is the name of the variable. To declare more than one variable of the specified types, used the comma separated list.


For Example:-
int v=10;                      //Here v is variable  
int a,b,c;                      //  declare three variable a,b, c and its data types is integer

Types of Variable
There are three types of variables in java
      1.   local variable
      2.  instance variable
      3.   static variable

1.Local Variable
A variable that is declared inside the method, constructor or block is called local variable.
A local variable are created when the method, constructor or block is entered and the variable will be destroyed once it exists the methods, constructor or blocks. And Access modifier cannot be used for local variables. A local variable are implemented at stack level internally.

For Example:- Here age is the local variable and this is defined in showAge() method. Its scopes is limited in the method only.

Public class Test{
Public void showAge()
    {
             int age=0;
         age=age+10;
         System.out.println(“Age is:-” +age);
             }
public static void main(String []args)
{
Test t=new Test();
t.showAge();
} }

Output:- Age is:- 10


2.Instance Variable
A variable that is declared inside the class but outside the method, constructor or block is called instance variable . It is not declared as static. An instance variable are also created when an object is created with the use of the key word  “ new” and it is destroyed when object is destroyed. And an access modifier can be used for instance variable. An instance variable have default value. For number the default values is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or with in the constructor.

  3.Static variable

<
A variable that is declared  with static keywords  is called static variable. It cannot be local.
There would only one copy of each class variable per class, regardless of how many objects  are created from it. Static variable are rarely used other than being declare as constant. Constant are variable that’s are declare as public/ private, final and static. A conatant variable  never change from initial values.

Example to understand the types of variables

class A
{  
int v=20;                                    //instance variable  

static int s=10;                        //static variable  

void method()
{  
int l=30;                                  //local variable  
}  
}


No comments:

Post a Comment