Command Palette

Search for a command to run...

Back to the lesson: Topic 15.6 — Logging Done Right
Core Java · Example 2 of 3 Java 8+

What string concatenation really costs

Nothing was ever printed, yet concatenation built 1000 strings. Placeholders defer formatting, but arguments are still evaluated: an expensive argument needs a supplier or a level guard. SLF4J behaves the same way.

Logging records what a running program did, so you can understand it in production where there's no debugger. Professional Java code logs through the SLF4J API with a back-end such as Logback, uses levels (TRACE to ERROR) to control volume, writes parameterized messages (log.info("Order {} placed", id)) instead of string concatenation, and passes exceptions as the last argument so their stack traces are kept.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a JUL Formatter subclass that formats records as LEVEL|logger|message and use it with your own handler to log three messages at different levels.

02

Write a method mask(String card) that keeps only the last four digits ("** ** 4242") and log a payment with the masked card number.

03

Write a JUL handler that counts records per level in a TreeMap and prints the counts after logging five messages.

Explain it without notes

01

Why use a logging framework instead of System.out.println?

02

Why should you write log.debug("x {}", x) instead of log.debug("x " + x)?

03

How should an exception be logged, and what goes wrong otherwise?

04

What is SLF4J, and why do libraries depend on it instead of on Logback?

05

What is the MDC, and what is the common bug when using it with thread pools?

What string concatenation really costs Java 8+
Sign in to run this example in your browser.

Expected output

concatenation:   toString called 1000 times
placeholder:     toString called 0 times
placeholder arg: expensiveSummary called 1000 times
supplier:        expensiveSummary called 0 times
guarded:         expensiveSummary called 0 times