如何阻止Java自动将char值转换为int? [英] How to stop Java from automatically casting a char value to an int?
本文介绍了如何阻止Java自动将char值转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
java编译器会自动将char值转换为int,这样的代码不会引发错误:
the java compiler automatically casts a char value into a int, code like this will not raise an error:
public void foo(int i){
// do something
}
char c = 'a';
foo(c);
是否有某种方法可以阻止编译器始终将char强制转换为int或引发错误?
Is there some way to stop the compiler from always casting chars to int or to throw an error?
推荐答案
By default, compiler does widening conversion for primitive types mentioned https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.2.
因此,它会自动将char转换为int.
So, it automatically converts char to int.
您可以通过在foo中使用Integer来避免这种情况. void foo(Integer i)
You can avoid it by using Integer in foo. void foo(Integer i)
这篇关于如何阻止Java自动将char值转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文