aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes One Question 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 "One Question " Watch "One Question " New topic
Author

One Question

Yojana
Greenhorn

Joined: Jun 12, 2000
Posts: 19
This program running perfectly but I am unable to understand the
program. Please anybody help me.
class MyClass
{
static int maxElements;

MyClass(int maxElements)
{
this.maxElements = maxElements;
}

}

public class Q19
{
public static void main(String[] args)
{

MyClass a = new MyClass(100);
MyClass b = new MyClass(100);

if(a.equals(b))
System.out.println("Objects have the same values");
else
System.out.println("Objects have different values");
}
}
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
Yojana,
could you please state what it is that you do not understand about the program, so people can you assist you in context ?
Herbert
Yojana
Greenhorn

Joined: Jun 12, 2000
Posts: 19
Hi Herbert!
According to me it should print "Objects have the same values" but it is printing "Objects have different values" why?
regards
Yojana

Surya B
Ranch Hand

Joined: May 10, 2000
Posts: 98
Hi Yojana,
The equals method which is used here is the equals method of the Object class,which is the root of the class hierarchy.All objects, including arrays, implement the methods of this class.So that is the main reason the compiler didn't flag an error in the first place when you used the equals method,though it was not defined in your class.So when you use equals in your code you are basically calling the Object class equals method which indicates whether some other object is "equal to" this one.In your case a,b are two different handles of the class MyClass and thats the main reason why it prints out "Objects have different values".If you want to print out "Objects have the same values" then you shoud override the equals method of the Object class.The class String also overrides the equals method of the Object class to implment its version.Hope my explanation is clear.
Surya

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: One Question