Menu
Coddy logo textTech

Advanced String Formatting

Part of the Logic & Flow section of Coddy's Java journey — lesson 49 of 59.

String formatting in Java allows you to create formatted strings using format specifiers. The most common ones are %s for strings, %d for integers, and %.2f for decimals.

Format a string with multiple values:

String name = "John";
int age = 25;
String text = String.format("Name: %s, Age: %d", name, age);

After executing the above code, text contains:

Name: John, Age: 25

Format decimal numbers with precision:

double price = 19.99;
String formatted = String.format("Price: $%.2f", price);

After executing the above code, formatted contains:

Price: $19.99

challenge icon

Challenge

Easy

Create a method named formatData that takes four arguments:

  1. A String (name) for a product name
  2. A double (price) for the product price
  3. An integer (quantity) for the amount
  4. A String (format) for output format type

The method should format the data based on these types:

  • "basic": return "ITEM: {name}, PRICE: ${price}"
  • "detailed": return "PRODUCT: {name}\nPRICE: ${price}\nQUANTITY: {quantity}"
  • "total": return "TOTAL FOR {quantity}x {name}: ${total}" (total = price * quantity) All prices should be formatted with exactly 2 decimal places.

Return message:

  • If any input is null or invalid format: return "Invalid input"

Cheat sheet

String formatting in Java uses format specifiers with String.format():

  • %s for strings
  • %d for integers
  • %.2f for decimals with 2 decimal places

Format strings with multiple values:

String name = "John";
int age = 25;
String text = String.format("Name: %s, Age: %d", name, age);
// Result: "Name: John, Age: 25"

Format decimal numbers with precision:

double price = 19.99;
String formatted = String.format("Price: $%.2f", price);
// Result: "Price: $19.99"

Try it yourself

import java.util.Scanner;

public class Main {
    public static String formatData(String name, double price, int quantity, String format) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        double price = Double.parseDouble(scanner.nextLine());
        int quantity = Integer.parseInt(scanner.nextLine());
        String format = scanner.nextLine();
        
        if (name.equals("null")) name = null;
        if (format.equals("null")) format = null;
        
        System.out.println(formatData(name, price, quantity, format));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow