Java String Concatenation: Rules, Examples, and Unicode Encoding - Quiz

Total: 5 questions

1. 

State the rule: when does the + operator perform string concatenation in Java, and when does it add numbers?

If at least one operand of + is a String, the operator performs concatenation: the other operand is converted to text (via String.valueOf) and the result is a new string. If both operands are numeric, ordinary arithmetic addition happens. A chain of + is evaluated left to right, so order matters: once an intermediate result becomes a string, every later + is concatenation too.

2. 

Why does 1 + 2 + "x" produce "3x", while "x" + 1 + 2 produces "x12"?

The + operator is left-associative and evaluated left to right. In 1 + 2 + "x", 1 + 2 is computed first (both numbers) = 3, then 3 + "x" = "3x". In "x" + 1 + 2, "x" + 1 is computed first = "x1" (the string has already "kicked in"), then "x1" + 2 = "x12". A number on the right does not switch the mode back to arithmetic — use parentheses if you need to add the numbers first.

3. 

Why can't you rely on == to compare the contents of two strings?

The == operator compares references (object addresses in memory), not the characters inside. Two strings with identical content can be different objects, in which case == returns false. To compare content, use str1.equals(str2) or Objects.equals(str1, str2) — the latter is null-safe. Sometimes == works by accident because of the string literal pool, but that is a quirk you must not depend on.

4. 

What is str += x equivalent to for a string str, and why avoid it in loops?

str += x is equivalent to str = str + x: x is converted to text, concatenated to the current value of str, and the str reference is reassigned to a new object. Because String is immutable, each step creates a new string. Inside a loop with many iterations this spawns lots of throwaway objects and is slow — reach for StringBuilder there instead.

5. 

How does the char type behave with the + operator?

It depends entirely on the other operand. If both operands are numeric (e.g. 'A' + 'B'), the char is promoted to int by its Unicode code point and arithmetic happens: 'A'=65, 'B'=66, result 131. But if at least one operand is a String (e.g. "" + 'A' + 'B'), the char is appended as a symbol, giving "AB". A char can also be written with a Unicode escape: 'A' is the same as 'A', and "AB" equals "AB".

Page 1 of 1