CodeBlanks Logo Icon CodeBlanks

System.out.printf

Learn formatted output with printf.

Formatted output with printf

System.out.printf produces tidy output using format placeholders. %s is for strings, %d for integers and %f for decimals. %n adds a platform-specific line break.

String name = "Ayşe";
int age = 30;
System.out.printf("Ad: %s, Yaş: %d%n", name, age);
// Ad: Ayşe, Yaş: 30

printf slots values into a pattern instead of concatenating pieces one by one, so the output is more readable. Unlike println, printf does not add a line break automatically; you use %n for that.

Format a decimal number

%.2f shows a decimal with two digits after the point. %8.2f sets the total width to 8 and right-aligns it, which is handy for aligning tables neatly.

double price = 19.5;
System.out.printf("Fiyat: %.2f TL%n", price);
// Fiyat: 19.50 TL

%.0f removes the fraction entirely and %,.2f adds grouping separators. This formatting is very useful for displaying money and statistics. printf does not change the value; it only formats how it appears.

Practice Format the price

Print the value double price = 19.5; using printf as Fiyat: 19.50 TL. Use two decimal digits and a line break.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    double price = 19.5;
    // print with printf using two decimals and a line break
  }
}

Sample solution

Main.java
System.out.printf("Fiyat: %.2f TL%n", price);

Expected output

Fiyat: 19.50 TL

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each placeholder to its type

Term Meaning
%s String
%d int
%f double
%n Line break

2 Format with two digits

Question
double price = 19.5;
System.out.printf("Fiyat: %____f TL%n", price);
Answer
double price = 19.5;
System.out.printf("Fiyat: %.2f TL%n", price);

Explanation: %.2f shows the decimal with two digits.

3 Which is a difference between println and printf?

  • printf uses a pattern and placeholders, println does not Correct answer
  • printf adds a line break automatically, println does not
  • println only prints numbers, printf only prints strings
  • they are exactly the same

Explanation: printf uses a format pattern and placeholders; println prints plain text as is.

All lessons in Beginner