Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem with equals????

 
Harvinder Singh
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//what will be the output and why???
class Eek {
static int nth;
public int i;
private double j;
Eek() {
i = nth; j = nth * 3.456; nth++;
}
public boolean equals(Object other) {
return (i == ((Eek)other).i);
}
public static void main(String[] args) {
Eek e1 = new Eek(); Eek e2 = new Eek();
e1.i = 1;
if (e1.equals(e2))
System.out.println("YES");
else
System.out.println("NO");
}
}
 
Jim Crawford
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok... here goes.
I'd say the output is YES, but I'm sure you confirmed with a compiler and JRE. I haven't yet.
Why:
Before e1 initialization the class is loaded and nth is set to 0.
On e1 initialization the member i is set to nth (0) and nth is incremented afterwards with i's value remaining 0.
On e2 initialization the member i is set to nth (1).
You then set i of e1 to 1 and since you overrided 'equals' it will return 1 == 1 (true), and print YES.
Was that what you were looking for?
Cheers.
[ January 14, 2004: Message edited by: Jim Crawford ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic