beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java String format() method explained with examples

By Chaitanya Singh | Filed Under: String handling

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 Tutorials

  • Learn Java
  • OOPs Concepts
  • Java Collections

Java String

  • Java String

Java String Methods

  • String charAt()
  • String compareTo()
  • String compareToIgnoreCase()
  • String contains()
  • String concat()
  • substring
  • String valueOf()
  • String startsWith()
  • String equals()
  • String format()
  • String endsWith()
  • String indexOf()
  • String lastIndexOf()
  • String length()
  • String replace()
  • String split()
  • String trim()
  • String intern()
  • String isEmpty()
  • String matches()
  • String regionMatches()
  • String contentEquals()
  • String toCharArray()
  • String getBytes()
  • String join()
  • String getChars()
  • String copyValueOf()

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap