![]() |
VOOZH | about |
Automatic type promotion in Java occurs when a smaller data type is automatically converted to a larger data type during method overloading. It helps the compiler choose the most suitable method when an exact match is not available. This feature ensures flexibility and avoids compilation errors in overloaded method calls.
int → long → float → double). Note:- This is important to remember is Automatic Type Promotion is only possible from small size datatype to higher size datatype but not from higher size to smaller size. i.e., integer to character is not possible.
Example: In this example, we are testing the automatic type promotion from small size datatype to high size datatype.
Automatic Type Promoted to Double-2.0
Explanation: Here we passed an Integer as a parameter to a method and there is a method in the same class that accepts double as parameter but not Integer. In this case, the Java compiler performs automatic type promotion from int to double and calls the method.
Example: Let's try to write a code to check whether the automatic type promotion happens from high size datatype to small size datatype.
Output:
Explanation: From this example, it is proven that Automatic Type Promotion is only applicable from small size datatype to big size datatype. As the double size is large when compared to integer so large size to small size conversion fails.
Example: In this example, we are going to look at the overloaded methods and how the automatic type of promotion is happening there.
Automatic Type Promoted to Integer-97 Automatic Type Promoted to Integer-2 Automatic Type Promoted to Double-2.0 Object method called
Explanation: In the above code,
char 'a' is promoted to int (97) and calls the int method.int value directly matches, so no promotion happens.float is promoted to double and calls the double method.String has no exact match, so it calls the Object method (no primitive promotion, uses inheritance).Example: In this example, consider the overloaded methods with more than one argument and observe how automatic type conversion is happening here:
Integer-Double Double-Integer
Explanation: In the above code,
These are the few examples that can give clear insight on Automatic type conversion in overloaded methods.