Witscale Test Center

9.3 Unary operators > 9.3.5 The cast () operator


9.3.5 The cast () operator

Casting is a very important concept in Java. Java is a typed language, there every value, expression, variable has a type. The cast operator is used when you want to change the type. Usually you can cast from one type to another type if they are cast-compatible. We will discuss cast compatibility in the next chapter. For now, you can simply remember that compiler allows you to cast to the similar types. For instance, you can cast any numeric type to other numeric type. Following code casts a float value to an int value:

 

   float exactTemp = 90.87;

   int approxTemp = (float) exactTemp; // value will be 90

 

The cast operator is a pair of round brackets. You can specify the type to which you want your expression to be cast in those brackets. Note that the above code will not compile without the cast operator. This is because the compiler can see the possible loss of precision when you store 90.87 into int value. You need to use the cast operator to assure the compiler explicitly that you know about the possible loss, but you still want the type to be changed. You can also use the cast operator to change the type of object references. This finishes our discussion of Java operators that operate on only one operand. Now let us turn our focus on the most common operators in Java, the binary operators.