Table of Contents
Type Conversion in Java
In Java, after assigning a value to one data type, the user may want to assign the same value to another data type. Here two cases may arise- the data types will either be compatible, or they will be incompatible. Now, if the two data types are compatible, Java itself will perform an automatic conversion called Automatic Type Conversion (as would be the case while assigning an int value to a long variable). On the other hand, if the data types are not compatible, then one data type needs to be cast or explicitly converted to another.
Automatic Type Conversion (Widening Conversion)
There are two scenarios when automatic interconversion between two compatible data types occurs- either the data types are compatible with each other, or we assign the value of a smaller data type to a bigger or larger data type.
In Java, numeric data types are all compatible with each other and can be subjected to Automatic Type Conversion. However, widening conversion is not possible for numeric to char or Boolean data types. As a matter of fact, char and Boolean are not compatible with each other.
Example:
class Demo { public static void main (String[] args) { int i = 100; long l = i; float f = l; System.out.println("Int value "+i); System.out.println("Long value "+l); System.out.println("Float value "+f); } }
Output:
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit Conversion
When we want to assign the value of a bigger data type to a smaller data type, we perform explicit type conversion or narrowing. When automatic conversions cannot be performed, and the data types are incompatible with each other, this kind of conversion becomes extremely important.
For example, if we try to interconvert char and int values, an error message will be displayed:
class Demo { public static void main(String[] argv) { char ch = 'c'; int num = 88; ch = num; } }
Output:
7: error: incompatible types: possible lossy conversion from int to char
ch = num;
How should one go about explicit conversions?
class Demo { public static void main(String[] args) { double d = 100.04; long l = (long)d; int i = (int)l; System.out.println("Double value "+d); System.out.println("Long value "+l); System.out.println("Int value "+i); } }
Output:
Double value 100.04
Long value 100
Int value 100
0 Comments