Skip to main content

Using printf to display text into the console


In this section, you'll learn how to use printf to control exactly how your output looks — decimal places, spacing, alignment, and more. By the end, you'll be able to format strings, numbers, and percentages like a pro.

What is printf?

printf stands for "print formatted." Unlike a regular print statement that just dumps text and numbers as-is, printf gives you control over how that data is displayed. Think of it as the difference between a plain T-shirt and a tailored outfit — same content, much better presentation.

The Basic Syntax

Every printf statement follows this structure:

System.out.printf("format-string", arguments);
  • format-string — defines how the output should look, combining plain text with placeholders for your data
  • arguments — the actual values you want inserted into those placeholders

Let's put this into practice with a few examples.

Example 1: Formatting a String

Start with something simple — printing a name inside a sentence:

String name = "Alice";
System.out.printf("Hello, %s! Welcome to our program.\n", name);

Here, %s acts as a placeholder for a string value. Run this code, and you'll see:

Hello, Alice! Welcome to our program.

Example 2: Formatting Numbers

Next, let's format a decimal number — useful when working with prices or measurements:

double price = 19.99;
System.out.printf("The price of the item is $%.2f.\n", price);

%.2f tells Java to round the number to two decimal places. The output:

The price of the item is $19.99.

This is especially important when working with currency, where extra or missing decimals can cause real problems.

Example 3: Aligning Text

Now try aligning text and numbers so they line up cleanly — useful for tables or lists:

String item = "Book";
int quantity = 5;
System.out.printf("%-10s %5d\n", item, quantity);
  • %-10s left-aligns the string within a 10-character space
  • %5d right-aligns the integer within a 5-character space

Output:

Book          5

Notice how everything stays neatly aligned — this becomes essential once you're printing multiple rows of data.

Example 4: Displaying Percentages

To display a value as a percentage, use %f combined with a literal %%:

double score = 0.856;
System.out.printf("Your score is: %.1f%%\n", score * 100);

%.1f%% rounds to one decimal place and appends a percent sign. Output:

Your score is: 85.6%

Try this the next time you need to display grades, statistics, or performance metrics.

Example 5: Combining Multiple Data Types

Finally, let's combine several data types in a single printf statement:

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);

Output:

Bob is 30 years old and 5.9 feet tall.

As you can see, printf lets you mix strings, integers, and decimals in one clean, readable statement.

Recap

You've now covered the core building blocks of printf:

Format Specifier Used For
%s Strings
%d Integers
%.2f Decimals (with fixed precision)
%-10s / %5d Alignment (left/right)
%% Literal percent sign

Try combining these in your own programs — once you get comfortable with formatting, your output will look far more polished and professional.

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...