Wednesday, 18 May 2016

Variable in java

A variable is name of  reserved area  allocated in memory. A variables are reserved the memory based on the data type. As we know that there are different types of data type used in java such as byte, short, int, char, float, etc.
There  are three  types of variables in java, which are :
1)  Local variable:
·         Local variable is declared within the methods, constructors and blocks.
·         We do not use any types of modifiers (public, private, Protected) for Local variable.
·         If  we are declared local variable in methods, constructors, and block, we have to initialize before use of local variables . 
·         There is no default value for local variable. .
·         Local variable is implemented at heap level memory.


public class Puppy{
public void PupAge(){ //Method
Int age=0;//Local variable
age=age+7;
System.out.println("puppy age is :"+age);
}
public static void main(string args[]){
Puppy p =new Puppy();
p.PupAge();
}
}
2)  Instance Variable:
·         Instance variable is declared outside of the methods, constructors and blocks.
·         It should be declared without using static keyword.
·         We can use any types of access modifiers in instance variable.
·         Default value of instance variable is zero.
·         Instance variable is implemented at stack level internally.

public class Puppy{
Int age//Instance variable

public void PupAge(){ //Method
age=age+7;
System.out.println("puppy age is :"+age);
}
public static void main(string args[]){
Puppy p =new Puppy();
p.PupAge();
}
}
3)  Static/Class Variable:
·         Static variable also known as class variable.
·         Static variable is declared outside of the methods, constructors and blocks.
·         We can use any types of access modifiers in static variable.
·         Default value of static variable is zero.
·         Static variable is implemented at static memory.

public class Test{
   public static void main(String args[]){
     Student s1 = new Student();
     s1.showData();
     Student s2 = new Student();
     s2.showData();
     
  }
}

class Student {
int a; 
static int b; 

  Student(){
   b++;
  }

   public void showData(){
      System.out.println("Value of a = "+a);
      System.out.println("Value of b = "+b);
   }


}

0 comments:

Post a Comment