Output formatting helps make program results clear and easy to read. It arranges text and numbers neatly on the screen.
Output formatting basics in 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.
System.out.printf("Hello %s!", "Alice");
System.out.printf("Price: $%.2f", 12.5);
System.out.printf("Count: %5d", 42);
System.out.printf("%-10s is cool", "Java");
This program prints a name left-aligned in 10 spaces, an age right-aligned in 3 spaces, and a score with 2 decimals.
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); } }
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.
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.