Java Typecasting


Typecasting

Converting one data type to another data type is known as typecasting. Since
Java is an Object-oriented programming language and supports both Inheritance and Polymorphism, it’s easy that superClass reference variable is pointing to a subClass object.

When we assign the value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then JVM will perform the conversion automatically known as automatic type conversion, and if not then they need to be cast or converted explicitly.

Types of Typecasting

Java, type casting is classified into two types.

1. Implicit Typecasting
Here, Automatic Type casting take place when the two types are compatible
the target type is larger than the source type.
Datatype precedence for implicit type casting (widening) is as follows :

byte -> short -> int -> long -> float -> double

Example

int i = 100; long l = i; //no explicit type casting required float f = l; //no explicit type casting required

2. Explicit Typecasting
When we assign a larger type value to a variable of smaller type, then we need to perform explicit typecasting. Datatype precedence for Explicit typecasting (narrowing) is as follows :

byte <- short <- int <- long <- float <-double

Example

double d = 100.04; long l = (long)d; //explicit type casting required int i = (int)l; //explicit type casting required

More Information:

This article needs improvement. You can help improve this article. You can also write similar articles and help the community.