Java String Formatting Example

Building strings from variables is a very common task in programming. Java language has the String.format() method to format strings.

Java String Formatting Example

public class StringFormatting {

    public static void main(String[] args) {
    
        int age = 29;
        String name = "Ramesh";

        String output = String.format("%s is %d years old.", name, age);
        
        System.out.println(output);
    }
}
Output:
$javac StringFormatting.java
$java StringFormatting
Ramesh is 29 years old.
We use the format() method of the built-in String class. The %s and %d are control characters which are later evaluated. The %s accepts string values, the %d integer values:
String output = String.format("%s is %d years old.", name, age);



Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course