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:

// Casting primitives
byte b = 4;
int i = b; // allowed because int is bigger than byte
 

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:

int i = 4;
byte b = i; // THIS WILL NOT COMPILE
 

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

int i = 4;
byte b = (byte) i; // This cast will allow compilation
 

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:

double d = 2.8;
int i = (int) d; // i will contain the value 2
 

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:

Animal leo = new Lion("Leo", Gender.MALE, 3); 

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:

Lion leo2 = leo; // WON'T COMPILE
Lion leo2 = (Lion) leo; // explicit casting to Lion
 

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


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Saturday, 13 December 2025

Captcha Image