String s = new String("5");
System.out.println(1 + 10 + s + 10 + 5);
output of the following function is 115105 how ?
String s = new String("5");
System.out.println(1 + 10 + s + 10 + 5);
output of the following function is 115105 how ?
"+" 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
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
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");
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.