首页 > 解决方案 > char 到 int 的隐式转换(或缺少转换)

问题描述

我正在为我的 OCA 考试而学习,并从 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");
    }
} 

以下代码的输出是什么?

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

正确答案是 (c),我在运行代码后也进行了验证。但是,为什么数据类型会在方法调用中char扩大到一个?int

根据我对Java中数据类型隐式转换的了解,默认情况下achar不会隐式转换为an int

TL;DR:为什么以下代码不起作用

int x = 5;
char c;
c = x; // Compliation error here

但这有效:

static void intParameterMethod( int someInt ) {}
public static void main( String args[] ) {
    char c = 5;
    intParameterMethod( c ); // No compilation error here
}

标签: java

解决方案


推荐阅读