Java Type Conversion

If you have previous programming experience, then you already known that it is fairly common to assign a value of one type to a variable of another type.

If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a long variable.

Java's Automatic Conversion

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met :

When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required.

For widening conversions, the numeric types, including the integer and floating-point types, are compatible with each other. However, there are no automatic conversion from the numeric types to char or boolean. Also, char and boolean are not compatible with each other.

Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char.

Type Conversion Example

Following program demonstrates the type conversion in Java :

/* Java Program Example - Java Type Conversion
 * This program demonstrates the Type Conversion
 * in Java
 */

class TypeConversionDemo
{
    public static void main(String args[])
    {
        
        char ch = 'A';
        int a, b = 68;
        long x;
        
        x = b;
        System.out.println("x(long) = b(int with value 68) : " + x);
        
        a = ch;
        System.out.println("a(int) = ch(char with value A) : " + a);
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java type conversion

Java Online Test


« Previous Tutorial Next Tutorial »