String Formatting
Part of the Fundamentals section of Coddy's Java journey — lesson 69 of 73.
In Java, String.format() is a powerful method used to create formatted strings. It allows you to combine text with variables in a readable and customizable way. This method uses format specifiers to define how variables should be inserted into the string.
The basic syntax of String.format() is:
String formattedString = String.format("format_string", arg1, arg2, ...);format_string: A string that contains text and format specifiers.arg1, arg2, ...: The variables to be inserted into theformat_string.
Here are some common format specifiers:
%s: Inserts a string.%d: Inserts a decimal (integer).%f: Inserts a floating-point number.
%b: Inserts a boolean value.%c: Inserts a character.%n: Inserts a newline character.
You can also control the formatting further:
%.2f: Formats a floating-point number with 2 decimal places.%10s: Inserts a string, right-aligned within a 10-character field.
%-10s: Inserts a string, left-aligned within a 10-character field.%03d: Inserts an integer, padded with leading zeros to a width of 3 digits.
Here's an example:
String name = "Alice";
int age = 30;
double price = 19.99;
String formatted = String.format("Name: %s, Age: %d, Price: %.2f", name, age, price);
System.out.println(formatted);
// Output: Name: Alice, Age: 30, Price: 19.99In this example, %s is replaced by name, %d by age, and %.2f by price, formatted to two decimal places.
Challenge
EasyCreate a method named createFormattedString that takes the following arguments:
- A string
productName. - An integer
quantity. - A double
unitPrice.
The method should return a formatted string that combines these values in the following format:
Product: [productName], Quantity: [quantity], Unit Price: [unitPrice]Format the unitPrice to five decimal places, the quantity with one decimal place (convert it to double).
For example, if productName is "laptop", quantity is 3, and unitPrice is 1299.9999, the method should return:
Product: laptop, Quantity: 3.0, Unit Price: 1299.99990To extract the first char while maintaining it in String type rather then char type use:
str.substring(0,1)
Cheat sheet
The String.format() method creates formatted strings by combining text with variables using format specifiers.
Basic syntax:
String formattedString = String.format("format_string", arg1, arg2, ...);Common format specifiers:
%s: String%d: Integer%f: Floating-point number%b: Boolean%c: Character%n: Newline
Formatting options:
%.2f: Float with 2 decimal places%10s: Right-aligned string in 10-character field%-10s: Left-aligned string in 10-character field%03d: Integer padded with leading zeros to 3 digits
Example:
String name = "Alice";
int age = 30;
double price = 19.99;
String formatted = String.format("Name: %s, Age: %d, Price: %.2f", name, age, price);
System.out.println(formatted);
// Output: Name: Alice, Age: 30, Price: 19.99To extract the first character as a string: str.substring(0,1)
Try it yourself
import java.util.Scanner;
public class Main {
public static String createFormattedString(String productName, int quantity, double unitPrice) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String product = scanner.nextLine();
int qty = scanner.nextInt();
double price = scanner.nextDouble();
String formattedString = createFormattedString(product, qty, price);
System.out.println(formattedString);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else