Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Confusion in == operator

Manoj Kumar Jain
Ranch Hand
Posts: 198
Hi All,

I am having this code from SCJP book of Kathy Sierra/Bert Bates, Chapter 4 exercise question no. 2

We need to insert the below fragments in code at line no. 7 :

And the following five code fragments:
F1. if(f1 == f2)
F2. if(f1 == f2[2][1])
F3. if(x == f2[0][0])
F4. if(f1 == f2[1,1])
F5. if(f3 == f2[2])
What is true?
A. One of them will compile, only one will be true
B. Two of them will compile, only one will be true
C. Two of them will compile, two will be true
D. Three of them will compile, only one will be true
E. Three of them will compile, exactly two will be true
F. Three of them will compile, exactly three will be true

Answer is D, that F2, F3, and F5 will compile, and only F3 is true.

I can understand for F2 and F5, but little bit confused why the F3 get compiled.

I read somewhere that first boxing takes place and then widening, so if we box the float f2[0][0] to Float we can't wide it to Long. Because there is no hierarchy relation in Long and Float.

are we unBoxing the Long x to long and then comparing it with float? but why ?

Winston Gutkowski
Bartender
Posts: 10527
64
Manoj Kumar Jain wrote:I read somewhere that first boxing takes place and then widening, so if we box the float f2[0][0] to Float we can't wide it to Long. Because there is no hierarchy relation in Long and Float.

To be honest, I forget all that stuff; but it makes more sense to me that Long would be unboxed to long and then widened to compare with a float, than that float would be boxed to a Float (particularly as the first will work and the second won't). I suspect that a thorough read of JLS Section 5 is in order though.

Winston

Manoj Kumar Jain
Ranch Hand
Posts: 198

Earlier I thought that it depends on the order of the objects being compared so I changed the comparison from if(x==f2[0][0]) to if(f2[0][0]==x) and its still working same way.

I think its always unboxing Long to long and then widening to compare with a float.

Also I changed the scenario little bit and run the below code which runs fine and evaluate to true:

so here are we first unboxing Float to float and then widening long to float. just to compare these two variables JVM is doing too much ?

Winston Gutkowski
Bartender
Posts: 10527
64
Manoj Kumar Jain wrote:so here are we first unboxing Float to float and then widening long to float. just to compare these two variables JVM is doing too much ?

Depends on your point of view. It's doing what it needs to. The real skill is to avoid the need to do it in the first place.

Winston