2

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
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Aniruddha Deb
  • 272
  • 2
  • 7
  • 5
    You can fit a char into an int. You may not be able to fit an int into a char. – Dave Newton May 15 '18 at 14:34
  • Ahh ok. My bad, stupid question. Should have checked that before posting. Thanks for helping me out :D Please submit your comment as an answer so that I can mark it correct. – Aniruddha Deb May 15 '18 at 14:36
  • The 'mechanic' behind this is called *widening*. A `char` can be widened into an `int`. The full list of widenings for primitives can be found [here](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.2) – Ben May 15 '18 at 14:36
  • https://stackoverflow.com/questions/27122610/why-does-the-java-api-use-int-instead-of-short-or-byte/27122853#27122853 – Steephen May 15 '18 at 14:44
  • @AniruddhaDeb No worries. All of this stuff can be found in the JLS--while not an exciting read (most of the time), pretty much all Java behavior is explained, if not always defended, within. – Dave Newton May 15 '18 at 14:46

0 Answers0