Variables types in Java

A class can contain any of the following variable types.
Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class variables:Class variables are variables declared with in a class, outside any method, with the static keyword.
class Point{
private int x; // instance variable
private int y; // instance variable
public static String coordinate; // Class variable
Point(){
this.x=0;
this.y=0;
this.coordinate=0+","+0;
}
Point(int _x,int _y){ // here _x and _y are local variables
this.x=_x;
this.y=_y;
this.coordinate=_x+","+_y;
}
public void show(){
String p="("+this.coordinate+")"; // here p is a local variable
System.out.println("Cordinate(x,y)="+p);
}
}
class Main{
public static void main(String[] arg){
Point p=new Point(3,4);
p.show();
System.out.println(Point.coordinate);
}
}
Class variable can be called directly without creating class Object or instance. In this example coordinate is class variable
Note: Instance variable cannot be called without creating class object or instance. In this example x and y are instance variables
Comments 12