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
Release: 2024-12-10 20:14:11
Original
420 people have browsed it

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");
Copy after login

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!

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