【问题标题】:Why does an int parameter allow passing a char value, but a char parameter doesn't accept passing an int value? [duplicate]为什么 int 参数允许传递 char 值,但 char 参数不接受传递 int 值? [复制]
【发布时间】:2016-07-13 15:04:47
【问题描述】:

当我声明一个Java方法时,为什么Java int参数接受传递的char值,而char参数不接受传递的int值?

例如:

// method which : int parameter
public static void printInt(int input) { 
    System.out.println(input);
}
// method which : char parameter
public static void printChar(char input) {
    System.out.println(input);
}

// main 
System.out.println("----------------------------------------");
printInt('a');      // print 97 [number of ASCII char 'a']
                    // int parameter accept char value
printChar(97);      // compilation error
                    // char parameter NOT accept int value
System.out.println("----------------------------------------"); 

【问题讨论】:

  • @khelwood 这是因为int 被认为比char“更宽”,因为它可以具有的值范围。注意:32 位的float 比 64 位的 long 宽。

标签: java methods parameters char int


【解决方案1】:

Implicit casting

由于int 足够大以容纳char 的所有可能值,因此将执行自动转换 - 这称为隐式转换,因此您无需执行任何操作用 char 调用该方法。

您可以使用显式强制转换:

printChar((char)97);

但要小心这种危险,除非您确定自己要达到的目标。

【讨论】:

  • 有一个(char) 1000 fileformat.info/info/unicode/char/3E8/index.htm 你的第一个解释是正确的,它不会将int 隐式转换为char
  • @PeterLawrey 和 @khelwood 更正了,我的错误
  • 注意:float 32 位比long 64 位宽,因为它的范围更广。字节数不是原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多