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 problem with equals???? 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 "problem with equals????" Watch "problem with equals????" New topic

problem with equals????

Harvinder Singh
Ranch Hand

Joined: Feb 14, 2003
Posts: 90
//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))

Hard work beats talent<br />when talent doesn't work hard.<p> - Tim Notke
Jim Crawford
Ranch Hand

Joined: Sep 08, 2002
Posts: 127
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.
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?
[ January 14, 2004: Message edited by: Jim Crawford ]

<img src="cool.gif" border="0"> <img src="graemlins/beerchug.gif" border="0" alt="[beerchug]" /> <br />SCJP 1.4
I agree. Here's the link:
subject: problem with equals????
It's not a secret anymore!