In 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.
The +
operator becomes String concatenation operator only if the left-hand side is the String
. Otherwise it remains the additive operator as per docs .
In your example 'c'
is a char literal, which gets promoted to int
during addition. Do note that c
is 99, not 119 as in your example so the output is 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.
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
:
System.out.println((99 + 1) + "Hello world");
^^^ ^
For that you get :
100Hello world
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.