Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java '+' operator between Arithmetic Add & String concatenation? [duplicate]

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
like image 307
ahmednabil88 Avatar asked Jul 13 '16 13:07

ahmednabil88


1 Answers

This isn't to do with string concatenation per se. It is about implicit casting to String. And it operates left to right, without implicit parentheses in the cases above. And String takes precedence over int.

Example 1

System.out.println("3" + 3 + 3);

Here, it begins with a string, so each operation after that is implicitly cast to string before doing the + operator. Hence, "333".

Example 2

System.out.println(3 + "3" + 3);

Same applies here, as the String takes precedence over the initial 3.

Example 3

System.out.println(3 + 3 + "3");

In this case, the first two numbers are added as they are ints, resulting in 6, but as it gets added to a String next, then it assumes concatenation, hence "63".

As per specification.

like image 78
ManoDestra Avatar answered Sep 19 '22 21:09

ManoDestra