• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why equal

 
Pres Brawner
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an example from a study guide I'm using:
Class XX {
int i, j;
static int z;
}
x1 = new XX();
x2 = new XX();
x3 = new XX();
x1.z = 10;
x2.z = 20;
if (x2.z > x1.z){
}
The if statement is false because the two statements are equal.
I could use some help understanding this.
Thanks.
 
Rex Rock
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable z is "static" in the class, so there will exist only one copy of it, for all the instances. so whenever u change the value of z , it will affect all instances. so when u compare, both will be 20
 
Jason Kretzer
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you declare a variable as a 'static' it makes only one copy of it for all instances of the class. This is a good way of keeping track of the number of instances of any one class. Anyway, first you changed z to 10. This made every class see z as being equal to 10. Then you made z equal to 20. Again, this changed the variable to 20 and now all classes will see it as 20.
Therefore, both of your classes in the 'if' statement are reading it as 20 and thus returning false.
Hope this sheds some light.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic