TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Use Java String Format with Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java BasicJava Tutorials

How to Use Java String Format with Examples

Last updated: Jun 01, 2024 9:19 pm
By Harsh S.
Share
11 Min Read
Java String Format Explained with Examples
SHARE

Hello friends, you can use three common ways to format strings in Java. This tutorial explains these methods: String’s format(), printf, and StringBuilder. It includes examples to demonstrate their usage and discuss the parameters, return types, and potential errors.

Contents
Basic String Formatting in JavaJava String Format SyntaxBasic String Format ExamplesUsing Different String Format SpecifiersFormat Date-Time String in JavaUsing %t for Date-Time FormattingJava Date-Time Formatting ExampleAdvanced String FormattingUsing printf for Stream OutputUsing StringBuilder for Complex FormattingComparison Java String Formatting MethodsRecommendationsBefore You Leave

Understand Different Ways to Format Strings in Java

String formatting in Java is primarily achieved using the String.format() method, which is similar to C’s printf function. It allows you to create formatted strings with placeholders for variables, making it easier to build complex output. Let’s dive into the different formatting options.

Basic String Formatting in Java

The most common choice to format strings in Java is to use the String class format() method. With this method, you can dynamically place another string, a number either integers or floats. Check the function syntax below:

Java String Format Syntax

SignatureDescription
Syntax
String.format(String format, Object... args)
Returns a formatted string using the specified format and arguments.
Arguments
format (String):
args (Object…):
The format string with placeholders.
One or more objects to replace the placeholders.
Return ValueReturns a formatted string.
Potential ExceptionsIllegalFormatException if the format string is illegal or incompatible with the arguments.
Java String Format Details

Basic String Format Examples

It is the most basic formatting shown in the below example.

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

This code will print: “Hello, John!”

In this example, the string is getting filled with integer numbers at runtime.

public class IntegerFormattingExample {
    public static void main(String[] args) {
        int age = 30;
        String formattedString = String.format("I am %d years old.", age);
        System.out.println(formattedString);
    }
}

This code will print: “I am 30 years old.”

This example is formatting a string with floating-point numbers.

public class FloatingPointFormattingExample {
    public static void main(String[] args) {
        double price = 29.99;
        String formattedString = String.format("The price is $%.2f", price);
        System.out.println(formattedString);
    }
}

This code will print: “The price is $29.99.”

Using Different String Format Specifiers

In Java, you can control the width, precision, and alignment of the formatted string by using additional specifiers. These specifiers are part of the format string.

  • %10s: Right-align a string within a 10-character-wide field.
  • %-10s: Left-align a string within a 10-character-wide field.
  • %5.2f: Format a floating-point number with a total width of 5 characters and 2 decimal places.

The below example shows how to use the specifiers with the Java string format method.

Runnable Code:

public class FormattingSpecifiersExample {
    public static void main(String[] args) {
        String city = "New York";
        int population = 8375000;
        double area = 468.48;
        String formattedString = String.format("%-15s | %10d | %8.2f", city, population, area);
        System.out.println(formattedString);
    }
}

This code will format and print data in a table-like manner:

New York        |    8375000 |   468.48

Format Date-Time String in Java

Java provides a separate class, SimpleDateFormat, for formatting date-time. However, we’ll discuss it separately. Here, let’s format a date-time string using the %t.

In the %t specifier, there is no direct use of “F” or “T” as standalone format flags. The correct way to use the %t specifier is in combination with other format flags to format dates and times in Java. Let’s clarify:

  • %t: The %t specifier itself is a placeholder that is used in conjunction with other format flags to format various date-time components. It doesn’t have a specific meaning on its own; it serves as a prefix for other format flags.

Using %t for Date-Time Formatting

When you use %t along with other format flags, you can format date-time components. For example:

%t SpecifierShort Description
%tFFormats the full date as “YYYY-MM-DD” (e.g., “2023-10-12”).
%tTFormats the full-time as “HH:MM: SS” (e.g., “12:34:56”).
%tYFormats the year with century as a base-10 number (e.g., “2023”).
%tmFormats the month as a base-10 number (01-12) (e.g., “10” for October).
%tdFormats the day of the month as a base-10 number (01-31) (e.g., “12”).
%tHFormats the hour of the day as a base-10 number (00-23) (e.g., “12” for 12 o’clock).
%tMFormats the minute as a base-10 number (00-59) (e.g., “34” for 34 minutes past the hour).
%tSTo format the second as a base-10 number (00-60) (e.g., “56” for 56 seconds).
Date-Time String Format Specifiers in Java

Java Date-Time Formatting Example

So, when you see %tF, it combines the date components to format the date in the “YYYY-MM-DD” pattern. Whereas, %tT combines the time components to format the time in the “HH:MM: SS” pattern. These format flags work in combination with %t displaying the desired output format for date-time components in Java.

Check out the below Java code exercising different options to format date-time values.

Runnable Code:

import java.util.Date;

public class DateTimeFormatExample {
    public static void main(String[] args) {
        // Create a Date object representing the current date & time
        Date currentDate = new Date();

        // Format and display date & time components
        String fullDate = String.format("Full Date: %tF", currentDate); // YYYY-MM-DD
        String fullTime = String.format("Full Time: %tT", currentDate); // HH:MM:SS
        String year = String.format("Year: %tY", currentDate); // YYYY
        String month = String.format("Month: %tm", currentDate); // MM
        String day = String.format("Day: %td", currentDate); // DD
        String hour = String.format("Hour: %tH", currentDate); // HH (00-23)
        String minute = String.format("Minute: %tM", currentDate); // MM (00-59)
        String second = String.format("Second: %tS", currentDate); // SS (00-60)

        // Display formatted date & time components
        System.out.println(fullDate);
        System.out.println(fullTime);
        System.out.println(year);
        System.out.println(month);
        System.out.println(day);
        System.out.println(hour);
        System.out.println(minute);
        System.out.println(second);
    }
}

In this code, we create a Date object representing the current date & time and use String’s format() to format and store various date & time components as strings. We then use System.out.println() to display the formatted date & time components as specified in the comments.

Advanced String Formatting

You will be happy to learn that Java provides some special ways to handle complex string formatting. Below are the step-by-step details on how to use these methods.

Using printf for Stream Output

The System.out stream provides a convenient way to format and print data using the printf method.

Item nameDescription
Method Description
PrintStream.printf(String format, Object... args)
Formats and prints a formatted string to the output stream.
Arguments
format (String)
args (Object…)
The format string with placeholders and specifiers.
One or more objects to replace the placeholders and specifiers.
Return ValueNone (void).
Potential ExceptionsNo checked exceptions, however, exceptions like FormatMismatchException, MissingFormatArgumentException, and IllegalFormatException may occur due to mismatches between format specifiers.
Java printf for formatting

Runnable Code:

public class PrintfStreamOutputExample {
    public static void main(String[] args) {
        String item = "Laptop";
        int quantity = 3;
        double itemPrice = 899.99;
        System.out.printf("Item: %s, Quantity: %d, Price: $%.2f%n", item, quantity, itemPrice);
    }
}

This code will format and print the item details, like “Item: Laptop, Quantity: 3, Price: $899.99.”

Using StringBuilder for Complex Formatting

For more complex formatting, you can use StringBuilder. It is more efficient when you need to concatenate multiple strings and format them.

Item nameDescription
Method Description
StringBuilder
A class for building strings with efficient concatenation.
ArgumentsNone
Return ValueA StringBuilder object.
Potential ExceptionsIt does not throw any checked exceptions. However, you get an IndexOutOfBoundsException if try to fetch a value that is out of the bounds.
Java StringBuilder Class

Runnable Code:

public class StringBuilderFormattingExample {
    public static void main(String[] args) {
        String name = "Veronica";
        int age = 25;
        String country = "Canada";

        StringBuilder formattedString = new StringBuilder();
        formattedString.append("Name: ").append(name).append(", Age: ").append(age).append(", Country: ").append(country);
        System.out.println(formattedString.toString());
    }
}

This code will produce the output: “Name: Veronica, Age: 25, Country: Canada.”

Comparison Java String Formatting Methods

Now, let’s compare the different string formatting methods and discuss which one is most suitable for specific scenarios.

MethodUse CaseProsCons
%s, %d, %f with String.format()Basic string, integer, and float formattingSimple and easy to useLimited control over formatting details
SimpleDateFormatDate & time formattingPrecise control over date/time formattingRequires additional classes and objects
printfStream output, simple formattingConvenient for simple outputLimited control for complex formatting
StringBuilderComplex and efficient formattingEfficient for concatenating multiple stringsRequires more code for simple cases
Java String Formatting Comparison

Recommendations

  • For simple, quick formatting, such as displaying a message with variables, using %s, %d, and %f is efficient and straightforward.
  • When dealing with date & time formatting, SimpleDateFormat provides precise control.
  • If you want to format and print data to the console, printf is a handy option for straightforward formatting.
  • For complex formatting scenarios, or when you need to concatenate multiple strings efficiently, StringBuilder is the way to go.

Before You Leave

String formatting is an essential skill in Java for creating well-structured and human-readable output. You will get to use it in almost every project in Java.

Feel free to copy and paste the code examples into your Java development environment to run and experiment with them.

Before you leave, render your support for us to continue. If you like our tutorials, share this post on social media like Facebook/Twitter.

Happy coding,
TechBeamers.

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Java ArrayList with Examples

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Choose the Best IDE for CPP IDE for CPP / C++ Programmers
Next Article Program to Reverse a Number using While Loop, Slicing, and Recursion Python Program to Reverse a Number

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x