A question was raised today in my computer science class. The question went something along the lines of:
If you print out two ints joined by a plus sign, are they added or are they printed out separately?
My initial response that if you did something like println(10 + 11); it would print out 1011. I was wrong, it doesn’t.
A brief example should clarify this.
int q = 10, w = 11; System.out.println( "" + q + w ); // 1011 System.out.println( q + w ); // 21 System.out.println( (q+w) ); // 21 System.out.println( "total = " + q + w ); // total = 1011 System.out.println( "total = " + (q + w) ); // total = 21
In the first print, I concatenate a string to an int and then to another int. This one prints out 1011. Why? Because the empty string is next to the int, and when one string is near a + operator, its nature changes and it will turn the int into a string and join them. Since 10 is now a string, 11 is joined as 10 was. In the next two lines, it shows that as I thought earlier, parentheses make no difference. And the final two show the difference when a string is involved along with parentheses.
To answer my class’ question, “If you print out two ints joined by a plus sign, are they added or are they printed out separately?” They are added.