Java Type Conversion

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

Java Type Conversion

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

Type of Type Conversion In Java

Implicit Conversion (Coercion)

Explicit Conversion (Casting)

java-Type-conversion

Implicit Conversion (Coercion)

In implicit or automatic conversion compiler will automatically change one type of data into another. Implicit or automatic conversion 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, conversion happens automatically. In implicit conversion a smaller type is converted into a larger thus it is also known as widening conversion.

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. Conversion 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.

Explicit Conversion (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 Conversion and its application with practical example. I hope you will like this tutorial.