Trusted answers to developer questions

How to cast in Java

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Casting is the act of converting one of the variables into another. There are two types of casting in Java:

Type hierarchy in Java

Before learning to cast variables, you should know the type hierarchy:

Type hierarchy
Type hierarchy

1. Implicit

Implicit casting is when you assign the value of the old variable, to the new variable, without any additional code. However, this is only valid if a narrower variable is being converted into a wider one (e.g. converting int into double). Polymorphism, when an object of a child (narrower) class is referred to by a reference variable of the parent (wider) class, is an example of this.

byte i = 10;
long newType = i;

2. Explicit

Explicit casting is the opposite of implicit casting. It is used when we have to convert a wider variable to a narrower one; but this time, we have to explicitly write the type we are converting to in (). Otherwise, a compile-time error will occur.

double d = 50;
int x = (int)d;

RELATED TAGS

cast
java
casting
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?