By Tony Bevis on Tuesday, 10 October 2023
Category: Java

Java programming course: 5.10 Casting

In the previous lesson you learnt about conditionals using the switch...case... block.

Casting

Enter your text here ...

You previously learned about the different capacities of the numeric primitive types, i.e., byte (8 bits), short (16 bits), int (32 bits), long (64 bits), char (16 bits), float (32 bits), double (64 bits).

The Java compiler is happy for you to copy a value from one of the above to a primitive of a different type provided that the receiving type has a larger capacity:

However, if you attempt to put the value of an int into a byte (or a short) the compiler will complain that the receiving variable might lose precision:

To overcome this, you need to cast the larger type into the smaller, which is achieved by specifying the receiving type in brackets:

In using the above syntax, you are effectively telling Java that you are aware of the potential loss of precision and are prepared to accept the consequences. You would only actually get a loss of precision if the value of the int variable i falls outside the bounds of byte, i.e., either less than -128 or greater than 127.

A similar situation occurs if you want to store a floating-point variable in an integer type, since to do so would lose the decimal places. Hence a cast would be required:

Casting objects

Casting may also be required for objects. Implicit casting you have used previously and can be a useful technique for increasing reuse and reducing maintenance:

Note that the receiving type for variable leo is declared to be Animal, but an object of type Lion actually gets instantiated. This is allowed because Lion is a subclass of Animal, or expressed in more everyday language a lion is a kind of animal.

If you now try to assign reference leo to a different reference of type Lion a cast is required:

The cast is effectively telling Java that although you defined reference leo to be of type Animal, you know that it is in fact a Lion reference.

In the next lesson you will learn about arithmetic operations on primitives.

Next lesson: 5.11 Arithmetic operations on primitives

Related Posts

Leave Comments