C

Core Java tutorial for beginners

Clean • Professional

Core Java – String Formatting in Java With Examples

3 minute

String Formatting in Java

In Java, string formatting allows you to create formatted text by embedding variables into strings in a clean and readable way. You can use it to control alignment, width, precision, and data type display.


1. Using String.format()

  • String.format() returns a formatted string without printing it directly.
  • It’s similar to printf but gives you a string that can be stored or reused.

Syntax

String formattedString = String.format(format, arguments);
  • format → A format string with placeholders (like %s, %d, %f)
  • arguments → Values to insert into placeholders

Common Placeholders

PlaceholderDescription
%sString
%dInteger
%fFloating-point number
%cCharacter
%bBoolean
%nNewline

Example – Basic String Formatting

public class StringFormatExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 25;
        double salary = 12345.678;

        String formatted = String.format("Name: %s, Age: %d, Salary: %.2f", name, age, salary);
        System.out.println(formatted);
    }
}

Output:

Name: Alice, Age: 25, Salary: 12345.68

Notes:

  • %.2f rounds the floating-point number to 2 decimal places.
  • String.format() does not print the string by itself.

2. Using printf()

  • printf() prints a formatted string directly to the console.
  • It works like String.format() but outputs immediately.

Syntax

System.out.printf(format, arguments);

Example – Using printf

public class PrintfExample {
    public static void main(String[] args) {
        String product = "Laptop";
        int quantity = 5;
        double price = 999.99;

        System.out.printf("Product: %s, Quantity: %d, Price: $%.2f%n", product, quantity, price);
    }
}

Output:

Product: Laptop, Quantity: 5, Price: $999.99

Notes:

  • %n adds a new line (platform-independent).
  • printf is often used for console-based reports and tables.

3. Formatting Examples

Align Text and Numbers

System.out.printf("|%-10s|%5d|%10.2f|%n", "Item", 12, 345.67);

Output:

|Item      |   12|    345.67|
  • %-10s → Left-align string in 10 spaces
  • %5d → Right-align integer in 5 spaces
  • %10.2f → Right-align float in 10 spaces with 2 decimals

Example – Multiple Lines in a Table

System.out.printf("%-10s %-10s %-10s%n", "Name", "Age", "Salary");
System.out.printf("%-10s %-10d %-10.2f%n", "Alice", 25, 12345.67);
System.out.printf("%-10s %-10d %-10.2f%n", "Bob", 30, 9876.54);

Output:

Name       Age        Salary
Alice      25         12345.67
Bob        30         9876.54

Notes:

  • Perfect for console-based reports and formatted tables.
  • Makes output readable and professional.

Points to Remember

  • String.format() → Returns formatted string (store or reuse).
  • printf() → Prints formatted string directly.
  • Use format specifiers (%s, %d, %f, etc.) to control output.
  • Control alignment, width, and precision for neat console output.
  • Use %n instead of \\n for cross-platform newlines.

🏆 Top 5 Interview Questions – String Formatting in Java

1. What is the difference between String.format() and printf() in Java?

Answer:

  • String.format() → Returns a formatted string that can be stored or reused.
  • printf() → Prints the formatted string directly to the console.
  • Both use format specifiers like %s, %d, %f.

2. Name some commonly used format specifiers in Java.

Answer:

SpecifierDescription
%sString
%dInteger
%fFloating-point number
%cCharacter
%bBoolean
%nPlatform-independent newline

3. How do you control the number of decimal places in a floating-point number?

Answer: Use %.nf where n is the number of decimals.

Example:

double price = 123.4567;
System.out.printf("%.2f", price); // Output: 123.46

4. How do you align text and numbers in formatted output?

Answer: Use width and alignment flags in format specifiers:

  • %-10s → Left-align string in 10 spaces
  • %10d → Right-align integer in 10 spaces
  • %10.2f → Right-align float with 2 decimals in 10 spaces

Example:

System.out.printf("|%-10s|%5d|%10.2f|%n", "Item", 12, 345.67);

Output:

|Item      |   12|    345.67|

5. Why is %n preferred over \\n in formatted output?

Answer:

  • %n produces a platform-independent newline, ensuring your program prints correctly on Windows, Linux, and macOS.
  • \\n may behave differently depending on the OS.

Article 0 of 0