Format String with String.format()
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
Another person
Another format
Standard format
Younger person
Another example
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public String solution(String name, int age) {
return String.format("Name: %s, Age: %d", name, age);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
