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

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

Barbara Streisand
Release: 2024-12-05 19:51:09
Original
343 people have browsed it

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

Formatting Strings in Java

Formatting strings to include placeholders for variables is a common task in programming. In Java, there are two primary ways to achieve this:

String.format

The String.format method accepts format specifiers and positional arguments to format a string. The syntax is as follows:

String.format(formatString, arguments...);
Copy after login

For example, to format a string like "Step {1} of {2}", you would use the following code:

String step = "1";
int totalSteps = 2;
String formattedString = String.format("Step %s of %s", step, totalSteps);
Copy after login

The format specifiers in String.format are similar to those found in C's printf family of functions:

  • %s - Insert a string
  • %d - Insert a signed integer (decimal)
  • %f - Insert a real number (standard notation)

System.out.printf

The System.out.printf method (a shorthand for PrintStream.printf) is similar to String.format, but it directly prints the formatted string to a stream, such as the console. The syntax is as follows:

System.out.printf(formatString, arguments...);
Copy after login

Note: Unlike C#, Java's format methods require positional arguments and do not support indexed placeholders (e.g., {0}). However, you can use the String.format method to store the formatted string and then print it using System.out.println or other methods.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template