-1

In Java :

System.out.println('c' + "Hello world" + 1);

gives

cHello world1

but

System.out.println('c' + 1 + "Hello world");   

gives

100Hello world

i.e 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.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 3
    If you add something to a string, it concatenates. That's the only time `+` concatenates. If you add a char to an int, it adds them numerically. – khelwood Aug 09 '18 at 14:35
  • Impossible. You can get `100`, not `120`. – BackSlash Aug 09 '18 at 14:40
  • take a look to [this SO question](https://stackoverflow.com/questions/21317631/java-char-int-conversions) – juanlumn Aug 09 '18 at 14:41
  • Well, not ASCII, UTF-16 (which is one of several character encodings for the Unicode character set). Java doesn't use ASCII. – Tom Blodget Aug 09 '18 at 22:39

2 Answers2

3

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.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
2

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140