Java Join Text Without Losing the Calculation
Concatenation builds text from values. For a larger sequence of additions, StringBuilder makes the construction explicit without repeatedly treating the accumulated text as a new immutable String.
Understand the idea
The + operator performs arithmetic for numeric operands and concatenation once a String participates. Evaluation proceeds according to grouping and operand order, so a label can change the meaning of a following +. StringBuilder is mutable and useful for assembling a result inside one method. It is not a thread-safe shared buffer by default. Escape sequences such as , , \" and \\ represent characters inside a string literal.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
public static void main(String[] args) {
int morning = 4, evening = 7;
StringBuilder report = new StringBuilder();
report.append("Bookings: ").append(morning + evening);
report.append("\nLabel: \"Workshop\"");
System.out.println(report);
}
}
Expected output
Bookings: 11
Label: "Workshop"The numeric addition happens inside the append argument, giving eleven. The builder then appends a new line and quoted text. println accepts the builder and uses its string representation. The visible quotation marks are part of the produced text; the backslashes that escape them belong to the Java source syntax.
Check the official Java documentation for detailed contracts and supported options.