Java Type Casting

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

Java Type Casting

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

Type of Type Casting In Java

Implicit Casting (Widening)

Explicit Casting (Narrowing)

Implicit Casting

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

Java--implicit-Type-Casting-Widening

In Java, there is no need of 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 a float. When we are assigning smaller type to a larger type, there is no need for explicit casting required, casting happens automatically .

Example:-

Here 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 right order (low to higher datatype). Type casting in wrong places may result in loss of precision, which the compiler can signal with a warning. for example like for instance truncating a float 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.

Recommended:-  Java if statement

Explicit Casting

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

Java-explicit-Type-Casting-Narrowing

Syntax :-

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

Example:-

Here, size of source type int is 32 bits and size of destination type byte is 8 bits. Since we are converting a source type having 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.