Course contentsShow
← Java
Lesson 2231 of 2,87043. String Handling in DepthFree lesson

Argument Indexing and Reuse

Using positional arguments like %1$s to reference the same argument multiple times in a format string.

Argument Indexing and Reuse

You'll learn how to reference the same argument multiple times in a format string using positional argument syntax.

The Core Idea

When formatting strings, you sometimes need to use the same value in multiple places within your output. Instead of passing the same argument multiple times, Java's formatting system allows you to reference arguments by their position using the syntax %n$s, where n is the 1-based index of the argument.

Think of it like a mail-merge document where you want someone's name to appear at the top and in the signature—you don't write the name twice; you reference the same source value in two locations.

Positional Argument Syntax

The format is: %position$conversionCharacter

  • %1$s references the first argument
  • %2$d references the second argument as a decimal integer
  • %3$f references the third argument as a floating-point number
String name = "Alice";
int score = 95;

// Using the same argument multiple times
String message = "Hello %1$s! Congratulations, %1$s, your score is %2$d!".formatted(name, score);
// Output: "Hello Alice! Congratulations, Alice, your score is 95!"

Why This Matters

Without indexing, you'd have to pass name twice:

// Less efficient approach
String message = "Hello %s! Congratulations, %s, your score is %d!".formatted(name, name, score);

Argument indexing makes your code cleaner and less error-prone when the same value appears multiple times.

String title = "Manager";
int years = 10;
String report = "%1$s with %2$d years. Promoted %1$s after %2$d years.".formatted(title, years);
// Output: "Manager with 10 years. Promoted Manager after 10 years."

Key Takeaway: Use %n$ syntax to reference arguments by position, allowing the same value to appear multiple times in a format string without redundant parameters.