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

equals method

ketki kalkar
Ranch Hand

Joined: May 09, 2007
Posts: 36
hi,
Which of the following prints "Equal"

A) int a = 10; float f = 10;
if ( a = = f) { System.out.println("Equal");}
B) Integer i = new Integer(10);
Double d = new Double(10);
if ( i = =d) { System.out.println("Equal");}
C) Integer a = new Integer(10);
int b = 10;
if ( a = = b) { System.out.println("Equal");}
D) String a = new String("10");
String b = new String("10");
if ( a = = b) { System.out.println("Equal");}

answer is A.Please explain.
Bill Cruise
Ranch Hand

Joined: Jun 01, 2007
Posts: 148
Answers B, C, and D are all using == to compare object references, so they will certainly not print "Equals".

The reason that answer A is correct is because the implicit casting rules for the == operator are the same as the arithmetic operators. In other words, if you had written

a + b

the compiler would have tried to cast to whatever type a is.

a == b works the same way.
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
->A and C are correct answers.

->B will give compiler error, you can't compare different Wrapper class
objects, using == operator. There will be incompatibility error.

->D will result false result, you are comparing two String object references, objects are created using new operator.

"A" refers to simple contract, even if the primitives are different but having
same value, they will be ==.

"C": after unboxing the comparison is done, resulting true.


Note: Why did you place a space between ==. It is == and not = =.
= = will give compiler error.


Thanks,


cmbhatt
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Bill Cruise

Answers B, C, and D are all using == to compare object references, so they will certainly not print "Equals".



Bill, are you sure C will not print "Equal"?

== operator will be applied after unboxing because one of the operand is
primitive. "a" will be unboxed, yielding value 10, so therefore there will
be comparison between two primitives that are having same values.


Thanks,
Bill Cruise
Ranch Hand

Joined: Jun 01, 2007
Posts: 148
Chandra,

You're absolutely right. I didn't account for autoboxing.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18724
    
  40

"ketki kalkar",

Please Quote Your Sources.

Thanks,
Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals method