gpt4 book ai didi

java - 如何打印字符的最大值?

转载 作者:行者123 更新时间:2023-11-29 09:53:47 25 4
gpt4 key购买 nike

虽然这是一个非常初级的问题,但我觉得它很复杂。其实我想知道幕后发生了什么?为什么 Character.MAX_VALUE 不打印 char 的最大值(即 65535)而 MAX_VALUE-1 打印。

    System.out.println("Byte Max Value: "+Byte.MAX_VALUE);//print 127 Ok!
System.out.println("Character Max Value: "+Character.MAX_VALUE);//print ?(Question Mark)
System.out.println(Character.MAX_VALUE-1);//print 65534

最佳答案

因为在第二行中,Character.MAX_VALUE 与字符串连接在一起。

作为JLS状态:

The string concatenation operator + (§15.18.1), which, when given a String operand and an integral operand, will convert the integral operand to a String representing its value in decimal form, and then produce a newly created String that is the concatenation of the two strings

由于 Character.MAX_VALUE 不可打印,因此您看不到它。

在第三种情况下,你用 int 做减法,因此整个表达式被转换为 int 并打印 int值(value)。

也作为JLS状态:

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

[...]

Binary numeric promotion is performed on the operands (§5.6.2).

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  1. [...]

  2. 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.

如果你完成了

System.out.println("Character Max Value: "+(Character.MAX_VALUE+0));

它将打印Character Max Value: 65535

关于java - 如何打印字符的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23413497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com