Saturday, June 26, 2010

Usage of Static in Java in SIMPLE

class A {
static int x = 100;
int y = 200;

void m1(){
//int Z; //this is wrong; a method local variable cannot be kept uninitialized.
int z = 300;
System.out.println(z);
}

static void m2(){
System.out.println("A");
}
public static void main(String[] args) {
A a = new A();
A b = null;//default value of object reference
System.out.println(a.x); //prints 100
System.out.println(a.y); //prints 200
a.m1();//prints 300
a.m2();//prints A
System.out.println(A.x);//prints 100 because int x is a static int
/*System.out.println(A.y);// compile error cannot referenced by the class name because its not static*/
/*A.m1();// compile error because it can not be referenced by the class name because its not static*/
A.m2(); //prints A
System.out.println(b.x);//prints 100
System.out.println(b.y);/*compies well but gives a run time error called nullObjectPointerException
* it also happens because y and m1() are not static. the reference of b is A*/
b.m1();//same as previous line
b.m2();//prints A

System.out.println(x);
// System.out.println(y);//compilation error
//m1();//compilation error
m2();//prints A
}



}


/*to understand this I recommend you to compile it and run then compare results with the code.:)*/

No comments:

Post a Comment