Java 为什么我在第3和第4个print语句中返回整数而不是字符?
你能解释一下最后两份打印报表的内容吗?那就是我迷路的地方Java 为什么我在第3和第4个print语句中返回整数而不是字符?,java,unicode,Java,Unicode,你能解释一下最后两份打印报表的内容吗?那就是我迷路的地方 public class Something { public static void main(String[] args){ char whatever = '\u0041'; System.out.println( '\u0041'); //prints A as expected System.out.println(++whatever); //prints B as
public class Something
{
public static void main(String[] args){
char whatever = '\u0041';
System.out.println( '\u0041'); //prints A as expected
System.out.println(++whatever); //prints B as expected
System.out.println('\u0041' + 1); //prints 66 I understand the unicode of 1 adds up the
//unicode representing 66 but why am I even returning an integer when in the previous statement I returned a char?
System.out.println('\u0041' + 'A'); //prints 130 I just wanted to show that adding an
//integer to the unicode in the previous print statement is not implicit casting because
//here I add a char which does not implicitly cast char on the returned value
}
}
'\u0041'+1
生成int
,您需要将其强制转换为char
,以便javac将调用绑定到println(char
)而不是prinln(int)
这是因为
当运算符将二进制数字提升应用于一对操作数(每对操作数必须表示可转换为数字类型的值)时,以下规则依次适用,必要时使用加宽转换(§5.1.2)转换操作数:
- 如果任何操作数为引用类型,则执行取消装箱转换(§5.1.8)。然后:
- 如果其中一个操作数的类型为double,则另一个操作数将转换为double
- 否则,如果其中一个操作数的类型为float,则另一个操作数将转换为float
- 否则,如果其中一个操作数的类型为long,则另一个操作数将转换为long
- 否则,两个操作数都将转换为int类型
基本上,两个操作数都转换为
int
,然后调用System.out.println(int-foo)
。+
,*
等可以返回的唯一类型是double
,float
,long
,int
whatever
是字符,+/whatever
表示whatever=whatever+1
(忽略前缀顺序)
System.out.println((char)('\u0041' + 1));
由于涉及赋值,所以将结果转换为char,因此调用char方法。但在第3-4次打印时,没有赋值,根据规则,所有的求和操作默认以int进行。因此,在打印操作之前,它对
char+char
和char+int
进行求和,并且由于没有返回赋值,因此在操作后仍保持为int,因此调用整数方法。因为char
s被铸造为int
。如果要连接这些值,请将它们转换为String
s。从char到int的转换在Java中是隐式的。Charecters只不过是整数。好的,那么最后一个print语句呢?unicode和“A”不被认为是同一类型吗?@KacyRaye。查看该链接中的最后一个条件。至少升级到int
。所以,任何二进制表达式的结果都可以是最小的int
类型。我和我学校的两位老师必须一起工作才能理解这个答案,但我们最终理解了你所说的一切。谢谢。