Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
20: String Formatting
I've spent a lot of time reviewing code from junior developers, and there is one pattern that consistently makes me sigh: "Plus-Sign Soup." This happens when someone tries to build a complex string—like a report or a log message—by chaining together dozens of + operators and escaped quotes.
The "Plus-Sign Soup" Misconception
The misconception is that string concatenation is the most direct way to build a formatted string. It feels intuitive at first. You just tack things on. But look at what happens when we try to build a simple financial transaction line:
String report = "Date: " + date + " | Account: " + accountId + " | Amount: $" + amount + " | Status: " + status;
System.out.println(report);
// Output: Date: 2023-10-01 | Account: 12345 | Amount: $1250.5 | Status: COMPLETED
It looks okay for one line, but it's a nightmare to maintain. If I ask you to right-align the amount so the decimals line up in a list, or to ensure the amount always shows two decimal places (even if it's $1250.50), you're suddenly importing DecimalFormat or doing weird math. The layout logic is tangled up with the data logic. It's messy, and frankly, it's hard to read.
Template-Based Formatting with Specifiers
The professional way to handle this is to use a template. Instead of building the string piece by piece, you define a "skeleton" of what the output should look like and then plug the values in. In Java, we do this primarily with String.format() or System.out.printf().
The magic happens with format specifiers. These are placeholders that start with a percent sign (%) and tell Java exactly how to treat the data. Here are the ones you'll use 90% of the time:
%s: A string.%d: An integer (decimal).%f: A floating-point number.%n: A platform-independent newline (better than\n).
Let's rewrite that transaction report using String.format(). This time, I'm going to add some "width" and "precision" modifiers to make it actually look like a professional report:
String date = "2023-10-01";
String accountId = "12345";
double amount = 1250.5;
String status = "COMPLETED";
String report = String.format("Date: %-10s | Account: %-8s | Amount: $%8.2f | Status: %s",
date, accountId, amount, status);
System.out.println(report);
// Output: Date: 2023-10-01 | Account: 12345 | Amount: $ 1250.50 | Status: COMPLETED
I'll break down those weird symbols for you, because this is where people usually get confused:
%-10s: The-means left-justify. The10means "make this field at least 10 characters wide." If the string is shorter, Java adds spaces.%8.2f: The8is the total width. The.2is the precision—it forces exactly two decimal places. This is the industry standard for handling currency displays.
I personally prefer String.format() when I need to store the result in a variable, but if you're just printing to the console for debugging or a simple CLI tool, System.out.printf() is a shorthand that does the exact same thing without needing the extra variable assignment.
One last pro tip: if you're dealing with large numbers, you can add a comma to the specifier (e.g., %,.2f). This will automatically insert thousands-separators based on the user's locale, which makes your software feel a lot more polished.
📋 Practical Task
Exercise: Professional Inventory Ledger Generator
You are building a tool for a warehouse manager. Your task is to create a program that prints a neatly aligned inventory table. You should not use string concatenation (the + operator) for the final output layout.
Requirements:
- Create three sets of variables:
itemName(String),quantity(int), andunitPrice(double). - Print a header line:
ITEM QTY PRICE - Use
System.out.printf()to print the data so that:- The item name is left-justified and takes up 15 characters.
- The quantity is right-justified and takes up 5 characters.
- The price is right-justified, takes up 10 characters, and is formatted to exactly 2 decimal places with a dollar sign prefix.
- Ensure each item appears on its own line.
Expected Output Example:
ITEM QTY PRICE
Widget A 50 $ 12.50
Super Gadget 12 $ 145.00
Small Bolt 1000 $ 0.25There are no comments for now.