java - Java 中的 char 和 int

标签 java

看到这段代码有效,我感到很惊讶。我认为 char 和 int 是 Java 中的两种不同的数据类型,我必须将 char 转换为 int 才能使 ascii 等效。为什么会这样?

String s = "hello";
int x = s.charAt(1);
System.out.println(x);

最佳答案

char 可以自动转换为 int。参见 JLS 5.1.2 :

The following 19 specific conversions on primitive types are called the widening primitive conversions:

...

  • char to int, long, float, or double

...

A widening conversion of a signed integer value to an integral type T simply sign-extends the two's-complement representation of the integer value to fill the wider format. A widening conversion of a char to an integral type T zero-extends the representation of the char value to fill the wider format.

(强调)

关于java - Java 中的 char 和 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8549692/

相关文章:

java - 使用拆分调节器拆分字符串数组

java - 占位符替换为内联(场景)变量,而不是全局(背景)变量

java - 如何在android中设置自定义颜色

java - Java 有什么好的多方法实现吗?

java - 如何让我的java程序输出答案?

java - Swing:如何创建不使用布局的可滚动 JPanel 列表

java - 如何在 main() 中访问私有(private)静态实例变量

java - 为什么 Java Streams min 方法不接受空值,即使使用的比较器是空友好的?

java - PHP 和 Java FileOutputStream 编写的文件

java - Android - 无法在启动屏幕上播放歌曲