Java Formatting Strings

JavaJavaBeginner
Practice Now

Introduction

In Java, the String.format() method formats a string using a combination of a formatting string, a locale, and arguments. The formatting string specifies the format the arguments should be converted to, and the locale specifies any settings that should be used, such as the language or region. In this lab, we will learn more about how to use the String.format() method to format strings.

Creating a Simple String Formatting Example

In this step, we will create a basic example of using the String.format() method to format a string.

  1. Create a new Java file named SimpleFormatExample.java in the ~/project directory.
  2. In the SimpleFormatExample class's main() method, create a string variable called formattedString and set it equal to the result of calling String.format() with the following arguments:
    1. The string "Hello, %s!" as the formatting string.
    2. The string "world" as an argument.
  3. Print out the value of formattedString using System.out.println().
  4. Save and close the SimpleFormatExample.java file.
  5. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  6. Then, run the class file using the command java SimpleFormatExample.

Here is the code:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("Hello, %s!", "world");
        System.out.println(formattedString);
    }
}

When you run the code, you should see the following output:

Hello, world!

Using Arguments in the Formatting String

In this step, we will learn how to use arguments in the formatting string to customize the output.

  1. Open the SimpleFormatExample.java file in an editor.
  2. Modify the formattedString variable to use an argument for the number of characters to display. Replace the "s" in the formatting string with ".%d-s" to specify the maximum number of characters to display.
  3. Add an integer argument after the formatting string to represent the maximum number of characters to display.
  4. Save and close the SimpleFormatExample.java file.
  5. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  6. Then, run the class file using the command java SimpleFormatExample.

Here is the modified code:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("Hello, %d-s!", 5);
        System.out.println(formattedString);
    }
}

When you run the code, you should see the following output:

Hello, 5-s!

Using Flags to Modify the Formatting Behavior

In this step, we will learn how to use flags to modify the behavior of the formatting string.

  1. Open the SimpleFormatExample.java file in an editor.
  2. Modify the formatting string to left-align the text by adding a minus sign (-) after the % sign.
  3. Add an argument to the formatting string to specify the minimum width of the output.
  4. Save and close the SimpleFormatExample.java file.
  5. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  6. Then, run the class file using the command java SimpleFormatExample.

Here is the modified code:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("%-10s, world!", "Hello");
        System.out.println(formattedString);
    }
}

When you run the code, you should see the following output:

Hello     , world!

Using Conversion Characters to Format Different Data Types

In this step, we will learn how to use different conversion characters to format different data types.

  1. Open the SimpleFormatExample.java file in an editor.
  2. Modify the formatting string to include a floating-point number using the %f conversion character.
  3. Add a floating-point number argument after the formatting string.
  4. Save and close the SimpleFormatExample.java file.
  5. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  6. Then, run the class file using the command java SimpleFormatExample.

Here is the modified code:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("The value of pi is approximately %f", 3.14159265359);
        System.out.println(formattedString);
    }
}

When you run the code, you should see the following output:

The value of pi is approximately 3.141593

Using Precision Modifiers to Control the Number of Digits

In this step, we will learn how to use precision modifiers to control the number of digits displayed in formatted output.

  1. Open the SimpleFormatExample.java file in an editor.
  2. Modify the formatting string to include a floating-point number using the %f conversion character. Add a precision modifier (%.2f) to display only two digits after the decimal point.
  3. Add a floating-point number argument after the formatting string.
  4. Save and close the SimpleFormatExample.java file.
  5. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  6. Then, run the class file using the command java SimpleFormatExample.

Here is the modified code:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("The value of pi is approximately %.2f", 3.14159265359);
        System.out.println(formattedString);
    }
}

When you run the code, you should see the following output:

The value of pi is approximately 3.14

Using Locales to Customize Formatting Settings

In this step, we will learn how to use locales to customize formatting settings, such as the language or region.

  1. Open the SimpleFormatExample.java file in an editor.
  2. Modify the formatting string to include a number and use the %d conversion character.
  3. Add an integer argument after the formatting string.
  4. Add a second argument to the String.format() method to specify the locale to use. Use the Locale.FRENCH constant to specify the French language.
  5. Save and close the SimpleFormatExample.java file.
  6. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  7. Then, run the class file using the command java SimpleFormatExample.

Here is the modified code:

import java.util.Locale;

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format(Locale.FRENCH, "Le nombre est %d", 123456789);
        System.out.println(formattedString);
    }
}

When you run the code, you should see the following output:

Le nombre est 123456789

Formatting Date and Time Values

In this step, we will learn how to use the String.format() method to format date and time values.

  1. Open the SimpleFormatExample.java file in an editor.
  2. Add an import statement for the java.util.Calendar class, which we will use to create a calendar instance.
  3. Create a new Calendar instance using Calendar.getInstance().
  4. Modify the formatting string to include a date using the %tD conversion character.
  5. Add a Date argument after the formatting string, using the calendar.getTime() method to get a Date value.
  6. Save and close the SimpleFormatExample.java file.
  7. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  8. Then, run the class file using the command java SimpleFormatExample.

Here is the modified code:

import java.util.Calendar;
import java.util.Date;

public class SimpleFormatExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        String formattedString = String.format("%tD", calendar.getTime());
        System.out.println(formattedString);
    }
}

When you run the code, you should see the following output:

08/22/21

Formatting Using Uppercase and Lowercase

In this step, we will learn how to use the %S and %s conversion characters to format strings in uppercase and lowercase, respectively.

  1. Open the SimpleFormatExample.java file in an editor.
  2. Modify the formatting string to include a string using the %S conversion character to format the string in uppercase.
  3. Modify the formatting string to include a second string using the %s conversion character to format the string in lowercase.
  4. Save and close the SimpleFormatExample.java file.
  5. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  6. Then, run the class file using the command java SimpleFormatExample.

Here is the modified code:

public class SimpleFormatExample {
    public static void main(String[] args) {
        String formattedString = String.format("The word %S is in uppercase and %s is in lowercase", "HELLO", "world");
        System.out.println(formattedString);
    }
}

When you run the code, you should see the following output:

The word HELLO is in uppercase and world is in lowercase

Handling Exceptions

In this step, we will learn about the exceptions that can be thrown when using the String.format() method, and how to handle them.

  1. Open the SimpleFormatExample.java file in an editor.
  2. Modify the formatting string to include a character using the %c conversion character.
  3. Add a character argument after the formatting string.
  4. Save and close the SimpleFormatExample.java file.
  5. In the terminal, compile the SimpleFormatExample.java file by running the following command: javac SimpleFormatExample.java.
  6. Then, run the class file using the command java SimpleFormatExample.

Here is the modified code:

public class SimpleFormatExample {
    public static void main(String[] args) {
        try {
            String formattedString = String.format("The character is %c", "too long");
            System.out.println(formattedString);
        } catch (Exception e) {
            System.out.println("An exception occurred: " + e.getMessage());
        }
    }
}

When you run the code, you should see the following output:

An exception occurred: UString.format: '%c' != java.base/java.lang.String

Summary

In this lab, we learned how to use the String.format() method to format strings in Java. We started by creating a simple example that used a formatting string and arguments to generate a string. We then learned how to use different conversion characters to format strings, as well as precision modifiers and flags to control the output. We also learned how to use locales to customize formatting settings and how to format date and time values. Finally, we discussed some of the exceptions that can be thrown when using the String.format() method and how to handle them.

Other Java Tutorials you may like