0
0
Javaprogramming~5 mins

Output formatting basics in Java

Choose your learning style9 modes available
Introduction

Output formatting helps make program results clear and easy to read. It arranges text and numbers neatly on the screen.

When showing prices with two decimal places like $12.50
When printing a table of data with columns aligned
When displaying dates or times in a specific style
When you want to add labels or units next to numbers
When you want to control how many digits show after a decimal point
Syntax
Java
System.out.printf("format string", values);

// or
System.out.format("format string", values);

The format string uses special codes like %d for integers, %f for floating numbers, and %s for strings.

You can add width and precision to control spacing and decimal places, for example %.2f shows 2 decimals.

Examples
Prints a string by replacing %s with "Alice".
Java
System.out.printf("Hello %s!", "Alice");
Prints a floating number with 2 decimals, showing "Price: $12.50".
Java
System.out.printf("Price: $%.2f", 12.5);
Prints an integer right-aligned in a space 5 characters wide.
Java
System.out.printf("Count: %5d", 42);
Prints a string left-aligned in a space 10 characters wide.
Java
System.out.printf("%-10s is cool", "Java");
Sample Program

This program prints a name left-aligned in 10 spaces, an age right-aligned in 3 spaces, and a score with 2 decimals.

Java
public class Main {
    public static void main(String[] args) {
        String name = "Bob";
        int age = 30;
        double score = 95.6789;

        System.out.printf("Name: %-10s Age: %3d Score: %.2f\n", name, age, score);
    }
}
OutputSuccess
Important Notes

Always match the format specifiers (%d, %f, %s) with the correct data type to avoid errors.

Use \n inside the format string to add a new line after printing.

Output formatting is useful for making your program's output look professional and easy to understand.

Summary

Use System.out.printf or System.out.format to format output in Java.

Format specifiers control how values appear, including alignment and decimal places.

Formatted output makes data easier to read and understand.