Home >Java >javaTutorial >How Do I Format Strings in Java Using `String.format` and `System.out.printf`?

How Do I Format Strings in Java Using `String.format` and `System.out.printf`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 20:14:11447browse

How Do I Format Strings in Java Using `String.format` and `System.out.printf`?

Formatting Strings in Java

Formatting strings in Java can be achieved using the String.format method. While it resembles the printf family of functions in C, it employs different format specifiers.

To format a string like "Step {1} of {2}", use the following syntax:

String.format("Step %s of %s", "1", "2");

Commonly used format specifiers include:

  • %s: Insert a string
  • %d: Insert a signed integer
  • %f: Insert a real number in standard notation

Unlike C#, which uses positional references with optional format specifiers, Java does not support inserting parameters at different positions.

For direct printing, you can use System.out.printf (or PrintStream.printf), which prints the formatted string output to the specified print stream.

The above is the detailed content of How Do I Format Strings in Java Using `String.format` and `System.out.printf`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn