Code Logo

Format String with String.format()

Published at25 Jul 2026
Java OOP Easy 0 views
Like0

Write a Java function that takes a name and age, and returns a formatted string using String.format(). The format should be "Name: {name}, Age: {age}". Use %s for string and %d for integer placeholders.

String.format() is a static method in Java that returns a formatted string using the specified format string and arguments. It is similar to C's printf function and uses the same format specifiers: %s for strings, %d for integers, %f for floating-point, %n for newline, and %t for date/time values.

String.format() creates a formatted string without needing to concatenate with +. It is more readable for complex formatting and handles type conversion automatically. The method uses java.util.Formatter internally and can produce locale-sensitive output using overloaded versions with Locale parameter.

Time complexity is O(n) where n is the length of the formatted string. Space complexity is O(n) for the result string. The format method parses the format string and converts each argument to its string representation according to the format specifier.

Edge cases include null arguments (prints "null"), integers that exceed the field width, special characters in strings, and ensuring the number of format specifiers matches the number of arguments.

Example Input & Output

Example 1
Input
"Bob",25
Output
Name: Bob, Age: 25
Explanation

Another person

Example 2
Input
"Eve",35
Output
Name: Eve, Age: 35
Explanation

Another format

Example 3
Input
"Alice",30
Output
Name: Alice, Age: 30
Explanation

Standard format

Example 4
Input
"Diana",22
Output
Name: Diana, Age: 22
Explanation

Younger person

Example 5
Input
"Charlie",40
Output
Name: Charlie, Age: 40
Explanation

Another example

Algorithm Flow

Recommendation Algorithm Flow for Format String with String.format()
Recommendation Algorithm Flow for Format String with String.format()

Solution Approach

class Solution {
    public String solution(String name, int age) {
        return String.format("Name: %s, Age: %d", name, age);
    }
}

Best Answers

java - Approach 1
class Solution {
    public String solution(String name, int age) {
        return String.format("Name: %s, Age: %d", name, age);
    }
}