Java '+' operator between Arithmetic Add & String concatenation?

ahmednabil88 :

As we know
Java '+' operator is used for both

  • Arithmetic Add
  • String concatenation

Need to know exactly expected behavior and applied rule when i used both together
When i try following java code

System.out.println("3" + 3 + 3);    // print 333    String concatenation ONLY
System.out.println(3 + "3" + 3);    // print 333    String concatenation OLNY
System.out.println(3 + 3 + "3");    // print 63     Arithmetic Add & String concatenation
Mena :

This is basic operator precedence, combined with String concatenation vs numerical addition.

Quoting:

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

The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

See language specifications here.

TL;DR

  • Operator precedence for + is from left to right
  • If any operand in a binary operation is a String, the result is a String
  • If both operands are numbers, the result is a number

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452656&siteId=1