-4
String s = new String("5");
System.out.println(1 + 10 + s + 10 + 5);

output of the following function is 115105 how ?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Guru
  • 39
  • 10

5 Answers5

4

"+" is left associative so

1 + 10 => 11(int)
11 + s => "115"(String)
"115" + 10 => "11510"(String) 10 is converted to String
"11510" + 5 = "115105"(String) 5 is converted to String 
Mohammad Alavi
  • 594
  • 6
  • 9
1

Your code effectively functions as integer summation as long as it's possible, because the evaluation process goes from left to right. Once the String is encountered, the function switches to concatenation.

1 + 10 + "5" + 10 + 5
= (1 + 10) + "5" + 10 + 5
= 11 + "5" + 10 + 5
= 115105
blagae
  • 2,342
  • 1
  • 27
  • 48
0
String s = new String("5");
System.out.println(1 + 10 + s + 10 + 5);

Since expressions are evaluated from left to rignt your code is same as

System.out.println((((1 + 10) + "5") + 10) + 5);

So first (1 + 10) is evaluated and since it is simple integer addition you are getting 11 so your code becomes

System.out.println(((11 + "5") + 10) + 5);

Now (11 + "5") is evaluated and since one of arguments is String, it is being concatenated and result will also be String. So 11 + "5" becomes "11"+"5" which gives us String "115".

So after that our code is same as

System.out.println(("115" + 10) + 5);

and again in ("115" + 10) one of arguments is String so we are getting "115"+"10" which gives us another String "11510".

So finally we are getting to the point where we have

System.out.println("11510" + 5);

which is same as

System.out.println("115105");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

(1 + 10)and 10 and 5 are regarded as three strings in your code

Alex
  • 1
  • 3
-1

Java casts the integers as a string when you include a string in the addition, it becomes concatenation. Try

import java.io.*;
import java.util.*;
import java.lang.*;

public class mainactivity {
    public static void main(String a[]) {
        String s = new String("5");
        System.out.println((1 + 10) + s + (10 + 5));
    }    
}

This should output 11515.

Patrick Murphy
  • 2,311
  • 14
  • 17