This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Ordinal Coparisons Question

Lydia Zhang
Greenhorn
Posts: 29
Hi guys,
I don't underestand why this code works? How to compare char to int, char to float?

Francisco A Guimaraes
Ranch Hand
Posts: 182
when dealing with non-boolean primitives, you can compare any of them with any other, because the smaller operand is promoted to the type of the greater.
Francisco

Francisco A Guimaraes
Ranch Hand
Posts: 182
I found a more precise rule in the JLS 5.6.2:

• 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.

• []�s
Francisco

Lydia Zhang
Greenhorn
Posts: 29
Thanks Francisco!
But I'm still confused of how to promote the char 'A' to int or float? Can you give me an example?

Jose Botella
Ranch Hand
Posts: 2120
There is a chapter in JLS 5 about conversions and promotions.

Let's say 'A' char is 0041 in hex (two bytes)
To convert to a bigger type add enough zeros to its left up to the number of digits in the target type:
0000 0041 This is an int (4 bytes) with the same value as the char 'A'.
If the number is negative you will have to add 1s instead.
Review the binary, hexadecimal and two's complement
formats if needed.

Lydia Zhang
Greenhorn
Posts: 29
Thanks Jose! The binary is my weakest point, I really don't know how to display a number into binary... I'll review it.