C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Format output using printf() specifiers - Java Program

public class PrintfFormatting {

    public static void main(String[] args) {

 

        int age = 25;

        double salary = 45678.9876;

        String name = "Anand Rao";

 

        System.out.printf("Name: %s\n", name);                    // String formatting

        System.out.printf("Age: %d years\n", age);                // Integer formatting

        System.out.printf("Salary: %.2f USD\n", salary);          // Floating value with 2 decimals

        System.out.printf("Salary (10 width): %10.2f USD\n", salary); // Right-aligned with width

        System.out.printf("Hex of age: %x\n", age);               // Integer in hexadecimal

        System.out.printf("Percentage: %.1f%% completed\n", 75.0); // Printing % symbol

    }

}

Output

 
OUTPUT :
Name: Anand Rao
Age: 25 years
Salary: 45678.99 USD
Salary (10 width):   45678.99 USD
Hex of age: 19
Percentage: 75.0% completed

Explanation of Code

printf() → Formatted Output

Java’s System.out.printf() prints formatted text similar to C’s printf().

General syntax:

printf("format specifier", values);

Common Format Specifiers Used

Specifier

Meaning

Example

%s

String

"Anand"

%d

Integer

25

%f

Floating number

12.34

%.2f

Float with 2 decimals

12.34

%10.2f

Width 10, 2 decimals, right aligned

" 12.34"

%x

Hexadecimal integer

19

%%

Print the % symbol

%

Line-by-Line Explanation

String formatting

System.out.printf("Name: %s\n", name);

  • Replaces %s with the string stored in name.

Integer formatting

System.out.printf("Age: %d years\n", age);

  • %d prints integers.

Floating point with 2 decimals

System.out.printf("Salary: %.2f USD\n", salary);

  • .2 → two digits after the decimal.

Right aligned float with width

System.out.printf("Salary (10 width): %10.2f USD\n", salary);

  • Total width = 10 characters
  • Right aligned by default
  • Keeps 2 decimal places

Hexadecimal formatting

System.out.printf("Hex of age: %x\n", age);

  • Converts integer → hexadecimal.

Printing % symbol

System.out.printf("Percentage: %.1f%% completed\n", 75.0);

  • Use %% to print a literal percent sign.