Beginner 15 min read

String Concatenation and Formatting

By the end of this lesson, you'll be able to:

  • Build a message by concatenating strings and variables
  • Use String.format() to build a message more readably
  • Explain when formatting is preferable to plain concatenation

Prerequisites: "Type Conversion vs Casting"

Concatenation, revisited

String name = 'Thabo';
Integer orderNumber = 4821;
String message = 'Hi ' + name + ', your order #' + orderNumber + ' is confirmed.';

This works, but gets harder to read as more variables join in — every + is a small interruption to the sentence you're building.

String.format() as an alternative

String message = String.format(
    'Hi {0}, your order #{1} is confirmed.',
    new List<String>{ name, String.valueOf(orderNumber) }
);

{0} and {1} are placeholders, filled in order from the list that follows. Note that String.format() expects String values in that list — non-string values (like our Integer) need converting first, using exactly the String.valueOf() you met last lesson.

A real business example: Retail

An order-confirmation message with several dynamic parts — customer name, order number, delivery date — is a natural fit for String.format(): the sentence structure stays visible and readable, instead of getting broken up by + operators every few words.

Trade-offs and when NOT to use this

For a simple, one- or two-variable message, plain + concatenation is often just as readable and involves less ceremony (no building a List). String.format() earns its keep once you have three or more variables, or when the same message template gets reused in multiple places.

Exercise

Using String.format(), build a message: 'Case #{caseNumber} was closed after {days} days.' — with caseNumber '00012345' and days 3.

Show hint

Remember: String.format() needs a List<String>, and days needs converting first with String.valueOf().

APEX

String Concatenation and Formatting Quiz

1. What must the values passed to String.format() be?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Beyond the + operator from Module 3, Apex offers String.format() for building messages with placeholders — often more readable than a long chain of + operators, especially once several variables are involved.