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
posted
0
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
posted
0
->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
posted
0
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
posted
0
Chandra,
You're absolutely right. I didn't account for autoboxing.