printf
stands for “print formatted.” Instead of just printing text and numbers as they are, printf
lets you specify how you want them displayed.
This can include setting decimal places, padding numbers, or aligning text. Think of it as giving your output a polished suit instead of just a plain T-shirt.
Basic Syntax of printf
Before we dive into examples, let’s look at the syntax:
System.out.printf("format-string", arguments);
- format-string: This is where you define how the output looks. You can include text and placeholders for your data.
- arguments: These are the values you want to display.
Now that we know the syntax, let’s check out some practical examples.
Example 1: Simple String Formatting
Here’s a simple way to print text:
String name = "Alice";
System.out.printf("Hello, %s! Welcome to our program.\n", name);
In this example, %s
is a placeholder for a string. When you run this code, it displays: Hello, Alice! Welcome to our program.
Example 2: Formatting Numbers
Want to print a number in a specific format? Check this out:
double price = 19.99;
System.out.printf("The price of the item is $%.2f.\n", price);
Here, %.2f
tells Java to display the number with two decimal places. Output: The price of the item is $19.99.
This is super useful for anything related to money!
Example 3: Aligning Text
Alignment matters. Check how we can align text to the right:
String item = "Book";
int quantity = 5;
System.out.printf("%-10s %5d\n", item, quantity);
%-10s
means left-align the string in a 10-character space, while %5d
right-aligns the integer. The output looks like this:
Book 5
This makes it look tidy, ensuring everything lines up nicely.
Example 4: Displaying Percentages
Displaying percent values? No problem!
double score = 0.856;
System.out.printf("Your score is: %.1f%%\n", score * 100);
Here, %.1f%%
shows the score as a percentage with one decimal place. The output will be: Your score is: 85.6%
.
This is handy for report cards or performance metrics.
Example 5: Combining Different Data Types
You can mix and match types in one printf
statement seamlessly:
String name = "Bob";
int age = 30;
double height = 5.9;
System.out.printf("%s is %d years old and %.1f feet tall.\n", name, age, height);
The output? Bob is 30 years old and 5.9 feet tall.
This method makes your program’s output more informative and engaging.