Java String Formatting Example

1. Introduction

String formatting in Java allows you to create formatted strings using various data types and control their layout. This tutorial will demonstrate how to format strings in Java using the String.format() method, which provides similar functionality to printf() in C.

Key Points

- String.format() allows you to format numbers, strings, and other data types into a formatted string.

- The method returns a formatted string based on a format specifier that includes placeholders for inserting variable values.

- Common placeholders include %s for strings, %d for integers, and %f for floating-point numbers.

2. Program Steps

1. Define various data types that will be used in the string.

2. Use String.format() to create a formatted string using these values.

3. Print the formatted string.

3. Code Program

public class StringFormattingExample {
    public static void main(String[] args) {
        // Define variables
        int year = 2023;
        double price = 19.99;
        String name = "Java Book";

        // Create a formatted string
        String formattedString = String.format("In %d, the price of '%s' was $%.2f", year, name, price);

        // Print the formatted string
        System.out.println(formattedString);
    }
}

Output:

In 2023, the price of 'Java Book' was $19.99

Explanation:

1. int year = 2023;, double price = 19.99;, String name = "Java Book";: Declare variables representing a year, price, and a book name.

2. String formattedString = String.format("In %d, the price of '%s' was $%.2f", year, name, price);: Uses String.format() to create a string. %d is used to insert the integer (year), %s to insert the string (name), and %.2f to format the floating-point number (price) to two decimal places.

3. System.out.println(formattedString);: Prints the formatted string to the console, showing how the variables are integrated into the text with specific formatting.


Comments