I was studying for my OCA exam and came across this problem from Mala Gupta:
class Course { void enroll(long duration) { System.out.println("long"); } void enroll(int duration) { System.out.println("int"); } void enroll(String s) { System.out.println("String"); } void enroll(Object o) { System.out.println("Object"); } }
What is the output of the following code?
class EJavaGuru { public static void main(String args[]) { Course course = new Course(); char c = 10; course.enroll(c); course.enroll("Object"); } } a. Compilation error b. Runtime exception c. int String d. long Object
The correct answer is (c), which I validated as well after running the code. However, why does the char
datatype get widened to an int
in the method call?
According to my knowledge of implicit conversion of datatypes in Java, a char
is not implicitly converted into an int
by default.
TL;DR: Why does the following code not work
int x = 5;
char c;
c = x; // Compliation error here
But this works:
static void intParameterMethod( int someInt ) {}
public static void main( String args[] ) {
char c = 5;
intParameterMethod( c ); // No compilation error here
}