Every way to build text
+ concatenation, printf and String.format, text blocks, String.join and StringBuilder: which fits which job.
- A few pieces, once →
+. Watch the order:"Total: " + a + bjoins,a + b + " items"adds first. - Numbers in columns, a fixed number of decimals →
String.format/printfwith format specifiers such as%8.2f. - Several lines of fixed text (JSON, SQL, a help message) → a text block
""". - A list joined with a separator →
String.join(", ", names). - Text built up in a loop →
StringBuilder;+=in a loop copies the whole string every pass.
Joining
Section
Output and formatting
println, + and printf.
Formal. In a Java expression, *, / and % bind tighter than
binary + and -, which bind tighter than the comparisons, which bind
tighter than &&, which binds tighter than ||. Operators of the same
precedence group left to right, except assignment, which groups right to
left. Operands are evaluated left to right, and && and || evaluate
their right operand only when the left one doesn't already decide the
result.
In plain English. Do multiplication, division and remainder before adding and subtracting, then work from the left, just as in school arithmetic. Brackets override everything, so when in doubt, add them.
Example. 2 + 3 * 4 is 14, 20 - 5 - 3 is 12, and 24 / 4 / 2 is
3. "Total: " + 2 + 3 is "Total: 23" because the left + meets a
String first, while 2 + 3 + " items" is "5 items".
Why this rule exists. A fixed, familiar order lets everyone read the same expression the same way, without brackets around every step.
Why + joins or adds depending on what came first.
Left to right, and a String turns every later + into joining.
Formatting and layout
Example
String.format("%-10s%8.2f", name, price)A %-code that says how to show one value.
Section
Formatting and text blocks
Columns, decimals, and multi-line literals.
Term
text block
A multi-line string literal between triple quotes.
Building in a loop
Section
StringBuilder
One growable buffer instead of a new string per +=.