Java - What is the result of 1 + 2 + "abc" and "abc"+ 1 + 2

Question

What is the result of

String str = 1 + 2 + "abc";

and what is the result of

String str = "abc"+ 1 + 2 ;


Click to view the answer

abc12
3abc

Note

If both the operands are numeric, the + operator performs numeric addition.

If either operand is a string, the + operator performs string concatenation.

The execution of an expression is from left to right unless overridden by using parentheses.

Demo

public class Main {
  public static void main(String[] args) {
    String str = "abc"+ 1 + 2 ;
    System.out.println(str);/*from   ww  w  .  j  a  va 2s  .c o m*/

    str = 1 + 2+ "abc" ;
    System.out.println(str);
  }
}

Result

Related Quiz