Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals method

 
ketki kalkar
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
->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,
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chandra,

You're absolutely right. I didn't account for autoboxing.
 
Henry Wong
author
Marshal
Pie
Posts: 21408
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"ketki kalkar",

Please Quote Your Sources.

Thanks,
Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic