Addition and Concatenation in Java

Course Curriculum

Addition and Concatenation in Java

Addition and Concatenation in Java

Try to predict the output of following code:

public class PrutordotAi
{
public static void main(String[] args)
{
System.out.println(2+0+1+6+"PrutordotAi");
System.out.println("PrutordotAi"+2+0+1+6);
System.out.println(2+0+1+5+"PrutordotAi"+2+0+1+6);
System.out.println(2+0+1+5+"PrutordotAi"+(2+0+1+6));
}
}

Explanation:
The output is

9PrutordotAi
PrutordotAi2016
8PrutordotAi2016
8PrutordotAi9

This unpredictable output is due the fact that the compiler evaluates the given expression from left to right given that the operators have same precedence. Once it encounters the String, it considers the rest of the expression as of a String (again based on the precedence order of the expression).

System.out.println(2 + 0 + 1 + 6 + “PrutordotAi”); // It prints the addition of 2,0,1 and 6 which is equal to 9
System.out.println(“PrutordotAi” + 2 + 0 + 1 + 6); //It prints the concatenation of 2,0,1 and 6 which is 2016 since it encounters the string initially. Basically, Strings take precedence because they have a higher casting priority than integers do.
System.out.println(2 + 0 + 1 + 5 + “PrutordotAi” + 2 + 0 + 1 + 6); //It prints the addition of 2,0,1 and 5 while the concatenation of 2,0,1 and 6 based on the above given examples.
System.out.println(2 + 0 + 1 + 5 + “PrutordotAi” + (2 + 0 + 1 + 6)); //It prints the addition of both 2,0,1 and 5 and 2,0,1 and 6 based due the precedence of ( ) over +. Hence expression in ( ) is calculated first and then the further evaluation takes place.

Comparison of Autoboxed Integer objects in Java (Prev Lesson)
(Next Lesson) Java Numeric Promotion in Conditional Expression
', { 'anonymize_ip': true });