BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java String format() method explained with examples

By Chaitanya Singh | Filed Under: java

Java String format() method is used for formatting the String. There are so many things you can do with this method, for example you can concatenate the strings using this method and at the same time, you can format the output of concatenated string. In this tutorial, we will see several examples of Java String format() method.

Syntax of format() method

public static String format(Locale l,
            String format,
            Object... args)

Returns a formatted string using the specified locale, format string, and arguments.

and

public static String format(String format,
            Object... args)

Returns a formatted string using the specified format string and arguments.

A Simple Example of Java String format() method

public class Example{  
   public static void main(String args[]){  
	String str = "just a string";  
		
	//concatenating string using format
	String formattedString = String.format("My String is %s", str);  
		
	/*formatting the  value passed and concatenating at the same time
	 * %.6f is for having 6 digits in the fractional part
	 */
	String formattedString2 = String.format("My String is %.6f",12.121);

	System.out.println(formattedString); 
	System.out.println(formattedString2);  
   }
}

Output:

My String is just a string
My String is 12.121000

Java String format() example of concatenating arguments to the string

We can specify the argument positions using %1$, %2$,..format specifiers. Here %1$ represents first argument, %2$ second argument and so on.

public class Example{  
   public static void main(String args[]){  
	String str1 = "cool string";
	String str2 = "88";
	/* Specifying argument positions. %1$ is for the first argument and
	 * %2$ is for the second argument
	 */
	String fstr = String.format("My String is: %1$s, %1$s and %2$s", str1, str2);
	System.out.println(fstr);
   }
}

Output:

My String is: cool string, cool string and 88

As you can see that how we have passed the string “cool string” twice in the format() method using the argument positions format specifiers.

Left padding the string using string format()

In this example, we are left padding a number with 0’s and converting the number to a formatted String. In the above example we have formatted the float numbers and Strings and in this example we are formatting an integer. The important point to remember is that the format specifiers for these are different.
%s – for strings
%f – for floats
%d – for integers

public class Example{  
   public static void main(String args[]){  
	int str = 88;
	/* Left padding an integer number with 0's and converting it
	 * into a String using Java String format() method.
	 */
	String formattedString = String.format("%05d", str);
	System.out.println(formattedString);
   }
}

Output:

00088

Displaying String, int, hexadecimal, float, char, octal value using format() method

In the following example, we are using different format specifiers to display values of different types. Here we have shown few examples of how an integer value can be converted into an octal or hexadecimal value using format() method. After this example, we have shared a list of available format specifiers.

public class JavaExample {  
   public static void main(String[] args) {  
	String str1 = String.format("%d", 15); // Integer value  
	String str2 = String.format("%s", "BeginnersBook.com"); // String  
	String str3 = String.format("%f", 16.10); // Float value  
	String str4 = String.format("%x", 189);  // Hexadecimal value  
	String str5 = String.format("%c", 'P');  // Char value  
	String str6 = String.format("%o", 189); // Octal value
	System.out.println(str1);  
	System.out.println(str2);  
	System.out.println(str3);  
	System.out.println(str4);  
	System.out.println(str5);  
	System.out.println(str6); 
   }  
}

Output:
Java String format method example

Java String Format Specifiers

%c – Character
%d – Integer
%s – String
%o – Octal
%x – Hexadecimal
%f – Floating number
%h – hash code of a value

Related Posts:

  1. Java – left padding a String with spaces and zeroes
  2. Java – Right padding a String with spaces and Zeros

References:

  • String format() method – JavaDoc
  • Concatenate String using format() method
  • String format() padding example
❮ PreviousNext ❯

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap