技术咨询:为何字符与整数相加(如‘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 point71(you can remember this since'A'is65, 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
相关产品推荐
相关产品推荐

