The Java Quiz

with

a+=0.7f

the output doesn’t change. But you are on the right track…

1 Like

I’m betting it’s due to the check being floating point against double

1 Like
@zzuegg said: What is the output?

[java]
public class CompareTest
{
public static void main(String args)
{
float a = 0;
float b = 0;
a += 0.7;
b += 0.5;
if (a < 0.7) {
if (b < 0.5){
System.out.println(“Both smaller”);
}else{
System.out.println(“One smaller”);
}
}else{
System.out.println(“None smaller”);
}
}
}

[/java]

And a bonus point if you can say why…

Would that even compile?
I would bet that the double to float addition is against some JFC.

@t0neg0d said: I'm betting it's due to the check being floating point against double

Correct, you get a plus chris.
In the if check, the double gets not cast to float, but the float gets ‘upgraded’ to a double and

((double) 0.7f)<0.7d

@Empire Phoenix said: Would that even compile? I would bet that the double to float addition is against some JFC.

Indeed it does compile, probably because it there is no guessing from the compiler side is needed. When calling methods instead there could be overloaded methods and so you need to have the type defined.

@zzuegg said: Indeed it does compile, probably because it there is no guessing from the compiler side is needed. When calling methods instead there could be overloaded methods and so you need to have the type defined.

Well, the reason it’s strange is because:
float a = 0.5;

…would not be allowed, while:
float a = 0;
a += 0.5;

…is. Furthermore, the following won’t compile either:
a = a + 0.5;

…this is one of those places where Java is kind of inconsistent in what it allows.