Monday 2 November 2015

Java - Variable Types With Example

Variable is a name of reversed memory area of any values. In java values of variable can be change during execution of program.
In java there is three type variable

1. Local variable
2. instance variable
3. static variable

1. Local Variable :


i. Variable declare inside method is called local variable.
ii. These variable only access inside the specific method/block/constructor.
ii. Access modifiers cannot be used for local variables.

public class LocalVariable {
public static void main(String[] args) {
        LocalVariable localVariable = new LocalVariable();
       localVariable.display();
 }

     public void display(){
             int i = 10;// Local Varaible
             System.out.println(" i ="+i);
       }
}

Output:
 i =10

2. Instance variable :


i. Variable declare inside the class but outside method is called instance variable .
ii. Instance variable belongs to object , not to class.
Iii. Access modifiers can be used for instance variables.

public class InstanceVariable {
int i =20;
public static void main(String[] args) {
InstanceVariable instanceVariable = new InstanceVariable();
System.out.println(" instance variable ="+ instanceVariable.i);
}
}


Output :
instance variable = 20


3. Static Variable :


i. Variable declare inside class with static keyword is called static variable .
ii. Static variable can not local.
iii. Static variable belogs to class ,not to object.
iv. Access modifiers can be used for static variables.
v. Static varible access as ClassName.StaticVariableName

public class StaticVariable {
static int i =100;
public static void main(String[] args) {
System.out.println("price of bag is ="+ i);
}

}

Output :

price of bag is =100




Related Posts:




Exception Hanlding


File Handling

1 comment:

  1. what is reference variable and what are relation between reference variable and object,can you please clarify it giving memory diagram.

    ReplyDelete