-4
class TestStringConcatenation2
{
 public static void main(String args[]){

   String s=""+50+30+"Sachin"+40+40;
   System.out.println(s);
 }
}

The output is 5030Sachin4040 Why so?

4 Answers4

1

It's because you are treating each operand between + as String. If you want to calculate integer types and append them to String, you need to use brackets, in your case

s=""+ (50+30) +"Sachin"+ (40+40);

Coreggon
  • 505
  • 2
  • 5
  • 17
1

+ associates to the left. As such, this:

""+50+30+"Sachin"+40+40

is equivalent to

((((""+50)+30)+"Sachin")+40)+40

Java always evaluates left-to-right, so the most deeply nested bracket is evaluated first.

If either of the operands is a String, String concatenation is used. As such, the first bracket evaluates to "50".

((("50"+30)+"Sachin")+40)+40

Continuing with this rule (it's string concatenation if either operand is a string), the next bracket becomes "5030", etc.

(("5030"+"Sachin")+40)+40
("5030Sachin"+40)+40
"5030Sachin40"+40
"5030Sachin4040"

Had you omitted the leading "", the first bracket would have been 50+30, of which neither operand is a String, so numeric addition would have been used. But the second + would have been String concatenation, and it remains String concatenation thereafter. So, the result would have been:

(((50+30)+"Sachin")+40)+40
((80+"Sachin")+40)+40
("80Sachin"+40)+40
"80Sachin40"+40
"80Sachin4040"
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Quoting Java Language Specification for Additive Operators:

If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time

If the type of either operand of a + operator is String, then the operation is string concatenation.

Community
  • 1
  • 1
Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25
0

Let me explain..

"+" Is the only overloaded operator in Java which will concatenate Number to String. As we have 50 falling after the "" (that is an empty, not nulll, String) it is considering everything else as Strings

Alexius DIAKOGIANNIS
  • 2,465
  • 2
  • 21
  • 32