Java Type Casting

In this tutorial you will learn about the Java Type Casting and its application with practical example.

Java Type Casting

The conversion of a data type into another type is called typecasting. Type Casting is a mechanism that allows a variable of one data type to be converted to another data. When a variable is typecast into a different type, the compiler basically treats the variable as the new data type. Casting can only be performed, when they are compatible with the rules defined. Typecasting can be of two types.

Types of Type Casting In Java

Implicit Casting (Widening)

Explicit Casting (Narrowing)

Implicit Casting

An implicit or automatic casting compiler will automatically change one type of data into another. Implicit or automatic casting can happen if both types are compatible and the target type is larger than the source type.

Java--implicit-Type-Casting-Widening

In Java, there is no need for Explicit casting for the above sequence. For instance, if you assign an integer value to a floating-point variable, the compiler will insert code to convert the int to afloat. When we are assigning a smaller type to a larger type, there is no need for explicit casting required, casting happens automatically.

Example:-

Here the value of 'a' has been promoted from short to int and we have not had to specify any type-casting operator. implicit conversions affect primitive data types. Typecasting should always be used in the right order (low to higher data). Typecasting in the wrong places may result in a loss of precision, which the compiler can signal with a warning. for example like for instance truncating afloat when typecasting to an int. This can be avoided with an explicit conversion. In implicit casting a smaller type is converted into a larger thus it is also known as widening conversion.

Explicit Casting

There may be situations when we want to convert a value having a larger type to a smaller type. In this case, casting needs to be performed explicitly. Explicit casting allows you to make this type of conversion explicit, or to force it when it wouldn’t normally happen.

Java-explicit-Type-Casting-Narrowing

Syntax:-

To perform typecasting, put the desired type including modifiers inside parentheses to the left of the variable or constant you want to cast.

Example:-

Here, the size of source type int is 32 bits, and the size of destination type byte is 8 bits. Since we are converting a source type having a larger size into a destination type having less size, such conversion is known as narrowing conversion.

In this tutorial we have learn about the Java Type Casting and its application with practical example. I hope you will like this tutorial.