Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

cast
java
casting

How to cast in Java

Educative Answers Team

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:

svg viewer
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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring