Using String Format in Java

In Java, the String class offers the format() method, which facilitates crafting formatted strings via format specifiers. The structure for the String.format() method is String.format(format, arguments). Here, 'format' is a string containing regular text interspersed with one or more format specifiers, while 'arguments' are values designated to substitute those specifiers. Format specifiers commence with a % symbol and are succeeded by characters that denote the data type and its desired format. For instance, %s stands for a string, %d symbolizes a decimal integer and %f corresponds to a decimal floating-point number, among others. These specifiers can be augmented with flags, width, precision, and type indicators to refine the output further. Flags might encompass + (to invariably display a sign), 0 (for zero-padding), and - (for left justification), among others. The width outlines the minor character count to be written, while the precision, when paired with floating-point types, determines the decimal places limit. In this Java String Format Example, we employ String.format() to integrate the values from other variables into the string, followed by its display. Click Execute to run the Java String Format Example online and see the result.
Using String Format in Java Execute
public class StringFormatExample {
    public static void main(String[] args) {
        int age = 30;
        String name = "John";
        String formattedString = String.format("Hello, my name is %s, I am %d years old.", name, age);
Updated: Viewed: 44 times