Java int 转 char 输出真的很奇怪

标签 java char int

我在 int 到 char 转换方面遇到了一个奇怪的问题。这是我的代码:

    char a=100;
    System.out.println(a);
    System.out.println(a+1);
    System.out.println();

    System.out.println((char)a+1);
    System.out.println((char)101);
    System.out.println( (char)a+1==(char)101 );

它给了我这个输出:

d
101

101
e
true

这绝对是奇怪的:两个不同的输出在比较时似乎是相同的!为什么会这样呢?以及如何制作a+1被视为字符?

感谢您的回答,如果有一些英语错误,我很抱歉,这不是我的母语。

最佳答案

在这种情况下

System.out.println((char)a+1);

您只是将a转换为char(它已经是了)。加法使整个表达式成为一个 int,因此重载的 PrintWriter#println(int) 被执行。为了将其视为 char,请执行

System.out.println((char) (a+1));

In the JLS

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.

The type of an additive expression on numeric operands is the promoted type of its operands.

about promotion

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int.

关于Java int 转 char 输出真的很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479857/

相关文章:

c - 将负数打印为 C 中明确定义的字符吗?

ios - 在 Swift 中,如何使用传递给函数的 String 参数来引用 UILabel 变量?

java - 用户输入的数字不相加

c - 为什么 do (while number > 10) 中的 int 数字会导致无限循环?

JavaFX 显示 WebView 控件的 HTML 源代码

java - 连接 MySQL 时通信链路失败

java - 2020如何将media目录下的文件保存到外存?

java - 如何打印出所有线程及其当前状态?

c - 使用 C 返回数组

c - 通过将字符串类型转换为c中的int指针来获取字符串的长度