Java String format() Method

You are Here:

Java String format()

The format() method formats strings in a desired format by inserting objects and variables with specified padding into other strings.

Note: This method manages formatting including the position, alignment, and format type.

Example

Java Compiler
public class myClass { public static void main(String[] args) { String str = String.format("Name: %s", "John Doe"); System.out.print(str); } }

Output

Name: John Doe

Syntax

public String Format(str, obj1, obj2, ...)

Parameter Values

ValueTypeExplanation
strRequiredSpecifies a string.
obj1, obj2, ...RequiredSpecifies objects to replace one or more format items in a string.

Return Value

ValueExplanation
StringReturns a formatted string.

More Examples

We can specify that value (like an int) can be formatted inside String.Format().

Example

Java Compiler
public class myClass { public static void main(String[] args) { String str = String.format("Lucky Number: %d", 45); System.out.print(str); } }

Output

Lucky Number: 45

Formatting a string with specified padding.

Note: A negative number will add padding to the right (left-align). whereas, a positive padding size to add padding to the left (right-align).

Example

Java Compiler
public class myClass { public static void main(String[] args) { String str = String.format("Number with Padding: %10d", 45); System.out.print(str); } }

Output

Number with Padding: 45

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.

We are working to cover every Single Concept in Java.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author