# comparing primitives e.g 5.0 == 5L

Hans Beck�rus
Greenhorn
Posts: 24
Hi, I am preparing for the SCJP and is currently going trough
a book by Kathy Sierra and Bert Bates, "Sun Certified Programmer & Developer for Java 2".
In "Chapter 3: Operators and Assignments" there is an example like this:
System.out.println("5.0 == 5L? " + (5.0 == 5L));
which produces the following output:
5.0 == 5L? true
It is stated to compare a floating point to an int!
First question is this really true?
As I have understood it a primitive value of 5.0 is default
a double (64 bit integer) and 5L is a long which means it also is a
64 bit integer and not an 'int' in strict Java terms.
I can understand the fact that the comparison results in true but
then when I tested something like: 5.0 == (byte)5
it still evaluates to true!??
Are there not any constraints in Java when comparing primitives of
different types, e.g a double and a byte ?
I can understand if byte,char and int (and maybe also a long) can
be compared due to Java's propagation to int (32-bit?) but how
is it possible to compare a float and/or double with a standard
int? If I can recall correctly that is not even possible in
e.g. C/C++. Yes, I know Java is not C/C++, but in this case I am
confused about what rules Java is applying. Hence, the very
restrict way assignment like: byte a = 1; a = a + a; is! It
returns with "cannot convert from int to byte"

So, I am somewhat confused why comparison is not as strict as
assignment or is it so simple that I have just misunderstood
the whole thing?

wise owen
Ranch Hand
Posts: 2023
5.6.2 Binary Numeric Promotion

*If any of the operands is of a reference type, unboxing conversion (�5.1.8) is performed. Then:
*If either operand is of type double, the other is converted to double.
*Otherwise, if either operand is of type float, the other is converted to float.
*Otherwise, if either operand is of type long, the other is converted to long.
*Otherwise, both operands are converted to type int.

Vaibhav Chauhan
Ranch Hand
Posts: 115
//System.out.println("5.0 == 5L? " + (5.0 == 5L));
//which produces the following output:
//5.0 == 5L? true
This reason for getting true is:
whenever there is any comparison or any aritmetic operation, the type of operand gets converted to the higher one in the operation, therefore, 5L is getting converted to double(5.0 is treated as literal double).

same is with:
// 5.0 == (byte)5

//byte a = 1; a = a + a;

in the above code result of a+a is treated as integer(byte,short,char gets converted to int inn arithmetic operation) which ofcourse can not be assigned to byte a without casting.

Hans Beck�rus
Greenhorn
Posts: 24
Thanks for the quick slap
The jls seems to be a must have in my inventory
It is 'the' book I have been looking for.

So if I understood this correct, 5.0 == 5L
actually promotes the 5L to a double.
That was the answer to why 5.0 == (byte)5 also evaluated
to true since the byte was promoted to double before