How is the String.format() method used in Java?

The String.format() method in Java is used to create a formatted string by specifying a format string and providing arguments that will replace the format specifiers in the format string. Here's how it works:

  1. Format String: This is a string that contains format specifiers (like %s, %d, etc.) that define how the arguments should be formatted.
  2. Arguments: These are the values that will replace the format specifiers in the format string.

Example

Here's a simple example demonstrating the use of String.format():

public class FormatExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 30;
        String formattedString = String.format("My name is %s and I am %d years old.", name, age);
        System.out.println(formattedString); // Output: My name is Alice and I am 30 years old.
    }
}

In this example:

  • %s is used for a string (the name).
  • %d is used for an integer (the age).

You can use various format specifiers to format different types of data according to your needs.

0 Comments

no data
Be the first to share your comment!