top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Java String Format

Introduction

Java is a versatile programming language that offers a wide range of features for developers. One powerful aspect of it is its ability to handle command line arguments, which allows programs to receive input directly from the user when they are executed. In this comprehensive guide, we will explore the usage of Java command line arguments, with a particular focus on formatting strings using the String.format() method. By understanding the various format specifiers and techniques, you can enhance your string manipulation capabilities in Java. So let's dive in!

Overview

Before we delve into the intricacies of string formatting, let's start with a brief overview of Java command line arguments. When you execute a Java program from the command line, you can provide additional data or parameters known as command line arguments. These are passed as strings and can be accessed by the program at runtime. They allow you to customize the behavior of your program without modifying its source code.

Formatting Strings using String.format() Method

The String.format() method in Java is a powerful tool for manipulating strings with ease. It enables you to construct formatted strings by specifying format specifiers that act as placeholders for the values you want to insert. Let's explore some commonly used format specifiers:

  • Java string format {0}: This placeholder allows you to substitute the first argument in the formatted string.

  • Java string format Curly braces ({}) are used to enclose the format specifiers.

  • %s: This specifier is used for inserting strings.

  • %d: This specifier is used for inserting integers.

  • %f: This specifier is used for inserting floating-point numbers.

  • %x: This specifier is used for inserting hexadecimal numbers.

  • %n: This specifier represents a platform-specific line separator.

Examples of using String.format() to format Strings

To illustrate the usage of String.format(), let's consider an example where we want to display a personalized greeting message. We can achieve this by using the Java string format placeholder  to substitute the user's name:

public class JavaStringFormatExample {
    public static void main(String[] args) {
        String name = "John";
        String greeting = String.format("Hello, %s!", name);
        System.out.println(greeting);
    }
}

Output

The code creates a variable name with the value "John". It then uses the String.format() method to format a greeting message by inserting the value of the name into the placeholder %s.

Padding and aligning Strings using format specifiers

In addition to inserting values, format specifiers can also be used to control the alignment and padding of strings. For example, let's say we want to display a list of products with their corresponding prices. We can align the product names to the left and pad the prices with spaces to create a neat tabular format:

public class JavaStringFormatExample {
    public static void main(String[] args) {
        String product1 = "Apple";
        String product2 = "Banana";
        double price1 = 0.99;
        double price2 = 1.25;

        String formattedString = String.format("%-10s %10s%n%-10s %10s", "Product", "Price", product1, price1, product2, price2);
        System.out.println(formattedString);
    }
}

Output:

The code creates a formatted string with two columns, "Product" and "Price", and aligns them using a width of 10 characters. It then inserts the values of variables product1, price1, product2, and price2 into the formatted string.

Formatting Numbers using String.format() Method

Apart from formatting strings, the String.format() method allows you to format various numeric types, including integers, floating-point numbers, and hexadecimal numbers.

Java string format integer:

public class JavaStringFormatExample {
    public static void main(String[] args) {
        int number = 42;
        String formattedNumber = String.format("The answer is: %d", number);
        System.out.println(formattedNumber);
    }
}

Output:

The code assigns the value 42 to the variable number. It then uses the String.format() method to create a formatted string with the placeholder %d representing an integer.

Formatting floating-point numbers

public class JavaStringFormatExample {
    public static void main(String[] args) {
        double pi = Math.PI;
        String formattedPi = String.format("The value of pi is approximately %.2f", pi);
        System.out.println(formattedPi);
    }
}

Output:

The code assigns the value of π (pi) to the variable pi and formats it as a string with two decimal places, then prints the formatted string "The value of pi is approximately 3.14" to the console.

Formatting hexadecimal numbers

public class JavaStringFormatExample {
    public static void main(String[] args) {
        int decimalNumber = 255;
        String formattedHex = String.format("The hexadecimal representation is: %x", decimalNumber);
        System.out.println(formattedHex);
    }
}

Output:

The code assigns the value of 255 to the variable decimalNumber and formats it as a hexadecimal representation using the String.format() method.

Specifying precision and width in number formatting

When formatting numeric values, you can specify precision and width to control the formatting precisely. For instance:

public class JavaStringFormatExample {
    public static void main(String[] args) {
        double value = 123.456789;
        String formattedValue = String.format("Formatted value: %.2f, Width: %10.2f", value, value);
        System.out.println(formattedValue);
    }
}

Output:

The code above demonstrates how to format a floating-point number with a precision of two decimal places and a width of ten characters.

Formatting Dates using String.format() Method

In addition to strings and numbers, the String.format() method also allows you to format dates using format specifiers. Let's see some Java string format examples in date formatting:

import java.time.LocalDate;
public class JavaStringFormatExample {
    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        String formattedDate = String.format("Today's date is: %tF", currentDate);
        System.out.println(formattedDate);
    }
}

Output:

In the code snippet above, the format specifier "%tF" formats the date in the ISO-8601 format (YYYY-MM-DD). The resulting output will be "Today's date is: 2023-06-09".

Formatting dates using format specifiers

Java provides various format specifiers to customize the date formatting according to your requirements. Here's an example that demonstrates the usage of some commonly used specifiers:

import java.util.Date;
public class JavaStringFormatExample {
    public static void main(String[] args) {
        Date now = new Date();
        String formattedDate = String.format("Current date and time: %tc%nYear: %tY, Month: %tB, Day: %td", now, now, now, now);
        System.out.println(formattedDate);
    }
}

Output:

In the code snippet above, "%tc" formats the complete date and time, "%tY" extracts the year, "%tB" retrieves the full month name, and "%td" displays the day of the month. 

Examples of date formatting using String.format()

To further illustrate the date formatting capabilities of String.format(), let's consider an example where we want to display a custom date format:

import java.util.Calendar;
public class JavaStringFormatExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2023, 5, 9); // June 9, 2023
        String formattedDate = String.format("Formatted date: %1$tb %1$td, %1$tY", calendar);
        System.out.println(formattedDate);
    }
}

Output:

In this example, "%1$tb" represents the abbreviated month name, "%1$td" represents the day of the month, and "%1$tY" represents the year.

The Formatter Class

The Formatter class in Java provides an alternative approach to formatting strings, numbers, and dates. It offers more flexibility and control over the formatting process. Let's explore the key aspects of the Formatter class:

  • Overview of the Formatter class in Java

The Formatter class serves as the central component for formatting operations. It provides methods for constructing formatted strings and writing them to various output destinations.

  • Creating and using a Formatter object

To create a Formatter object, you can pass different types of destinations, such as OutputStream, File, or StringBuilder. Here's an example that demonstrates the creation of a Formatter object:

import java.util.Formatter;
public class Main {
    public static void main(String[] args) {
        Formatter formatter = new Formatter(System.out);
        
        String name = "Alice";
        int age = 25;
        double salary = 5000.50;
        
        formatter.format("Name: %s, Age: %d, Salary: %.2f", name, age, salary);
        
        formatter.close();
    }
}

Output: 

In the code snippet above, we create a Formatter object and use its format() method to construct a formatted string.

Syntax and parameters of Java String format() function

The syntax of the Java String format() function is straightforward. It takes a format string as the first parameter, followed by the values to be inserted into the placeholders. Let's examine the syntax and parameters in detail:

  • format: A string containing the format specifiers and literal text.

  • arg1, arg2, ...: Values to be inserted into the placeholders defined in the format string.

The return value of Java String format()

The Java String format() function returns a formatted string based on the specified format string and arguments. It does not modify the original string. Here's an example that demonstrates the return value of the format() function:

String formattedString = String.format("Value: %d", 42);
System.out.println(formattedString);

In the code above, the format() function constructs a formatted string with the value 42 inserted. The resulting string is assigned to the formattedString variable and then printed.

Exceptions of Java String format()

The Java String format() function can throw a runtime exception if the format string is invalid or if the arguments are incompatible with the format specifiers. For example:

try {
    String formattedString = String.format("Invalid format: %d", "text");
    System.out.println(formattedString);
} catch (IllegalFormatException e) {
    System.err.println("Invalid format: " + e.getMessage());
}

In the code above, an IllegalFormatException will be thrown since we are trying to insert a string argument into a placeholder expecting an integer value.

Use of Java String format() with locale

The format() method in Java also allows you to specify a locale for localized formatting. By providing a locale, you can ensure that the formatting adheres to specific language and cultural conventions. Here's an example:

import java.util.Locale;
double value = 1234.56;
Locale locale = new Locale("fr", "FR");
String formattedValue = String.format(locale, "Valeur formatée: %.2f", value);
System.out.println(formattedValue);

In this example, we specify the French locale using the "fr" language code and "FR" country code. The formatted value will be "Valeur formatée: 1234,56" with a comma as the decimal separator.

Conclusion

Java command line arguments provide a convenient way to customize the behavior of your programs. By understanding the intricacies of Java string formatting using the String.format() method, you can manipulate strings effectively and create visually appealing outputs. We explored the usage of format specifiers, padding and aligning strings, formatting numbers and dates, as well as the capabilities of the Formatter class. With this practical guide, you now have the knowledge to harness the power of Java string formatting and take your programming skills to the next level. So go ahead, experiment, and create beautifully formatted outputs in your Java applications.

FAQs

1. How to convert long to Java string format?

Ans: The different code snippets used to convert long to Java string format are the ‘+’ operator, Long.tostring(), string.valueOf(), new Long(longl), string.format(), and  DecimalFormat and the StringBuilder and StringBuffer append functions.

2. How can I format multiple arguments in Java String format?

Ans: To format multiple arguments in Java String format, you can include multiple placeholders in the format string and provide the corresponding values as additional arguments. For example, "Name: %s, Age: %d" expects two arguments, a string for the name and an integer for the age.

3. How can I specify decimal places in Java String format?

Ans: You can specify decimal places in Java String format by using the %f format specifier with precision. For example, "Value: %.2f" will format a floating-point number with two decimal places.

Leave a Reply

Your email address will not be published. Required fields are marked *