As we know
Java '+' operator is used for both
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With