[英]Output in java (System.out.println())
In Java : 在Java中:
System.out.println('c' + "Hello world" + 1);
gives 给
cHello world1
but 但
System.out.println('c' + 1 + "Hello world");
gives 给
100Hello world
ie c is converted to its ASCII character.What rule does Java use for this?Can someone tell me the set of rules which I can follow to predict the output as this has become quite confusing for me. 即c转换为它的ASCII字符。Java为此使用什么规则?有人可以告诉我我可以遵循的一组规则来预测输出,因为这对我来说很混乱。
The +
operator becomes String concatenation operator only if the left-hand side is the String
. 仅当左侧是String
, +
运算符才成为String串联运算符。 Otherwise it remains the additive operator as per docs . 否则,它仍然是docs的加法运算符。
In your example 'c'
is a char literal, which gets promoted to int
during addition. 在您的示例中, 'c'
是一个字符文字,在加法过程中被提升为int
。 Do note that c
is 99, not 119 as in your example so the output is 100Hello world
. 请注意, c
是99,而不是您的示例中的119,因此输出为100Hello world
。
because char
in Java play two roles one as a String when you concatenate it with a String and the second as an int when you sum it with another numeric value. 因为Java中的char
扮演两个角色,一个角色与字符串连接时作为字符串,第二个角色与另一个数值求和时作为int。
So in your case : 因此,在您的情况下:
System.out.println('c' + 1 + "Hello world");
Is equivalent to : 相当于:
System.out.println(('c' + 1) + "Hello world");
^ ^
where 'c' transform it to 99
: 'c'将其转换为99
:
System.out.println((99 + 1) + "Hello world");
^^^ ^
For that you get : 为此,您得到:
100Hello world
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.