Variables in Java
wat is the difference between class or static , instance and local variables?
Instance variables are the variables that are declared inside the class ( not inside the method)
instance variable with static keyword is called class/static variable
variables that are declared inside the method…which doesn’t have access outside the method are called local variables.
public class Simple
{
public static int a=10; // class or static variable
int b=66; // instance variable
public void method1()
{
int c=73; // local variable
}
public static void main(String[] args)
{
Simple s= new Simple();
// calling a class variable (this will print 10)
System.out.println(“Class variable :”+a);
// calling a instance variable(this will print 66)
System.out.println(“Instance variable :”+s.b);
// we cant call a local variable since it is local to method1()
}
}
Output:
Class variable :10
Instance variable :66
Few more doubts…
// calling a class variable (this will print 10)
System.out.println(“Class variable :”+a);
// calling a instance variable(this will print 66)
System.out.println(“Instance variable :”+s.b);
Why can’t I call ‘a’ also as ‘s.a’ ? What is the effect of ‘static’ keyword in ‘a’ ?
Thanks
yea. Since “a” is static variable it can be called directly inside a static method . we can also call as s.a nothing wrong bt it
is waste of memory space. by creating an object and calling the static variable, it can be called directly.
non static variables can be called by using objects.
public class Program
{
private static int x = 1;
private int y = 3;
public static void main(String args[])
{
Program p=new Program();
System.out.println(“Static variable”+ x);// calling a static variable
System.out.println(“non-Static variable”+p.y);// calling a non static variable using class object “p”
}
}
Static variables maintains single copy for all the instances. (i.e) common to all objects.
variables that are declared inside the static methods are static.
example :
public class Program
{
private static int x = 0;
private int y = 0;
public Program()
{
x++;
y++;
System.out.println(“non-static variable: “+y + ” static variable: ” + x);
}
public static void main(String args[]){
Program p1 = new Program();
Program p2 = new Program();
Program p3 = new Program();
}
}
output:
non-static variable: 1 static variable: 1
non-static variable: 1 static variable: 2
non-static variable: 1 static variable: 3