File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why equal Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why equal" Watch "why equal" New topic

why equal

Pres Brawner
Ranch Hand

Joined: Jan 18, 2001
Posts: 92
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.
Rex Rock
Ranch Hand

Joined: Jun 25, 2001
Posts: 82
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

Joined: May 31, 2001
Posts: 280
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.

Jason R. Kretzer<br />Software Engineer<br />System Administrator<br /><a href="" target="_blank" rel="nofollow"></a>
I agree. Here's the link:
subject: why equal
It's not a secret anymore!