object question

The following code from a MCQ

class hasstatic{

privatestaticint x=100;

publicstaticvoid main(String args[]){

hasstatic hs1=new hasstatic();

hs1.x++;//1

hasstatic hs2=new hasstatic();

hs2.x++;//2

hs1=new hasstatic();

hs1.x++;//3

hasstatic.x++;//4

System.out.println("x="+x);//5

}

}

When i compile and run the code i got the answer as x=104.

"But when i dry run the code i thought the result will be 101 because line 4 code will increase the original x value which will be printed in line 5 and line 1,2,3 will not effect the x because they are seperate objects which will have seperate variable X."

Can anyone give me a explanation for what realy happening inside the code and why my assumption is wrong.

[1435 byte] By [ram102125a] at [2007-11-27 5:59:51]
# 1

> because they are seperate objects which will have seperate variable X.

They are all separate objects, but they share the int x. That's what the "static" means. So hs1.x++, hs2.x++ and hasstatic.x++ are all incrementing the same variable.

(Note: Capitalisation is important. HasStatic. Also expressions like hs1.x++ are not very nice when HasStatic.x++ is available. If the MCQ did not make these points clear, it is most cr@ppy indeed.)

pbrockway2a at 2007-7-12 16:36:59 > top of Java-index,Java Essentials,New To Java...
# 2

because x is a static. static means we can access those method or variable with out reference. so variable x share same memory lacation.

then when you run that code:

class hasstatic{

private static int x=100;

public static void main(String args[]){

hasstatic hs1=new hasstatic();

hs1.x++; //here x=101

hasstatic hs2=new hasstatic();

hs2.x++; //here x=102

hs1=new hasstatic();

hs1.x++;//here x=103

hasstatic.x++;//here x=104

System.out.println(x) //print 104

System.out.println(hs1.x) //also print 104

System.out.println(hs2.x)// also print 104

}

}

but if you write like this it will print 101

class hasstatic{

private int x=100; //remove static;

public static void main(String args[]){

hasstatic hs1=new hasstatic();

hs1.x++;//1

hasstatic hs2=new hasstatic();

hs2.x++;//2

hs1=new hasstatic();

hs1.x++;//3

hasstatic.x++; //Error

System.out.println(x) ;//Compile Error because you can't access normal variable into static method with out reference

System.out.println(hs1.x); //print 101

System.out.println(hs2.x);//print 101

}

}

jeyrama at 2007-7-12 16:36:59 > top of Java-index,Java Essentials,New To Java...