What is going on here? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is going on here?

I Don't understand What is going on in this code. public class Program { public static void main(String[] args) { System.out.print((1 + "1") + 1 +1); } } The output is 1111. But why? What happens with the sum of 1 + 1? why is not 112?

28th May 2017, 6:34 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
4 Answers
+ 10
All "+" operator are treated as concatenate operator After a string literal. (1 + "1")+1+1 As you can see "1" this is a string literal here so all "+" use to append all the number. //Output 1111
28th May 2017, 6:57 PM
Fuyuka Ayumi(冬花)
+ 4
The last two 1s will be appended to the string 11 one by one.
28th May 2017, 6:49 PM
Tamás Barta
Tamás Barta - avatar
+ 3
Changing the string to a 2 to make this easier to read, I think the result step by step is: (((1 + "2") + 1) + 1) ((1"2") + 1) + 1) (1"2"1) + 1 1"2"11 1211
28th May 2017, 6:38 PM
Joseph P French
Joseph P French - avatar
+ 1
I understand right now, thanks!!
28th May 2017, 7:10 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar