You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术咨询:为何字符与整数相加(如‘G’+2)运行输出为73?

Why does System.out.println('G' + 2); output 73 in Java?

Great question! Let's walk through exactly what's happening here, since it boils down to how Java handles character and integer operations under the hood.

The Core Reason: Characters Are Integers in Java

In Java, the char data type isn't just a "character" — it's actually a 16-bit unsigned integer that represents a Unicode (UTF-16) code point. When you perform arithmetic operations between a char and an int, Java automatically converts the char to its corresponding integer value first.

Step-by-Step Breakdown of the Operation

Let's break down 'G' + 2 line by line:

  • Convert the char to its integer value: The character 'G' corresponds to the Unicode code point 71 (you can remember this since 'A' is 65, so counting 6 steps forward gets you to 'G' at 71).
  • Perform the integer addition: Now we're just adding two integers: 71 + 2 = 73.
  • Print the result: System.out.println() takes this final integer value (73) and outputs it directly as a number.

Bonus: How to Get a Character Instead of a Number

If you wanted the result to be the character corresponding to 73 (which is 'I') instead of the number, you'd need to explicitly cast the result back to a char:

System.out.println((char)('G' + 2)); // This outputs 'I'

内容的提问来源于stack exchange,提问作者Mados

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:00:27