Type Conversion in Java with Examples
Java, like any other dynamic language, supports a wide range of data types, including unsigned int, signed int, Boolean, char, int, float, double, long, and so on, with each data type requiring a different amount of memory space. When you assign the value of one data type to another, the two data types could not be compatible.
If the data types are compatible, Java will do the conversion automatically, a process known as automatic type conversion; if not they must be casted or converted explicitly. As an example, suppose you assign an int value to a long variable.
There are two types of Conversions.
- Automatic or Widening Type Conversion
- Narrowing or Explicit Type Conversion
Automatic Type Conversion or Widening:
When two data types are automatically transformed, this is referred to as widening conversion. This occurs when:
- The two data kinds are interchangeable.
- When we assign a value from a smaller data type to a larger data type.
For example, Numeric data types are compatible with Java, but no automated translation from numeric to char or Boolean is supported. Furthermore, char and Boolean are incompatible.
Implementation:
FileName: TypeConversion1.java
import java.io.*; import java.util.*; public class TypeConversion1 { public static void main(String[] args) { int i = 100; // Type conversion on automatically // Converting an integer to a long type long l = i; // Conversion of types automatically // convert long to float float f = l; System.out.println("The Integer value is " + i); System.out.println("The Long value is " + l); System.out.println("The Float value is " + f); } }
Output:
The Integer value is 100 The Long value is 100 The Float value is 100.0
Narrowing or Explicit Conversion:
We use explicit type casting or narrowing to assign a value from a larger data type to a smaller data type. This is helpful when dealing with incompatible data formats where automatic conversion is not possible.
The target type indicates the type to which the supplied value should be converted. The characters char and number are incompatible.
Implementation:
Filename: TypeConversion2.java
import java.io.*; import java.util.*; public class TypeConversion2 { public static void main(String[] args) { // double datatype double d = 100.04; // Explicit type casting by pushing data from a long datatype to an integer datatype long l = (long)d; // Performing Explicit type casting int i = (int)l; System.out.println("The Double value " + d); System.out.println("The Long value " + l); System.out.println("The Integer value " + i); } }
Output:
The Double value 100.04 The Long value 100 The Integer value 100