Introduction

In Java, we can format strings depending on our needs and get the required output. The printf command is very useful in Java. The printf command takes text as a string and formats it depending on the instructions given to it.

String Formatting

  • "%s" Format a string with the required number of characters.
  • "%10s" Format a string with the specified number of characters and also right justify.
  • "%-10s" Format a string with the specified number of characters and also left justify.
For formatting numbers, we use the "d" character and for floating-point numbers we use the "f" character.
Example
  1. package demo;
  2. public class Demo {
  3. public static void main(String args[]) {
  4. String n = "NAME";
  5. System.out.printf("%10s %n", n);
  6. }
  7. }
Output
string formatting right justify
Example
  1. package demo;
  2. public class Demo {
  3. public static void main(String args[]) {
  4. String n = "NAME";
  5. String l = "LOCATION";
  6. System.out.printf("%-10s %10s %n", n, l);
  7. }
  8. }
Output
string formatting left justify

Integer Formatting

  • "%d" Format a string with the required numbers.
  • "%5d" Format a string with the required number of integers and also pad with spaces to the left side if integers are not adequate.
  • "%05d" Format a string with the required number of integers and also pad with zeroes to the left if integers are not adequate.
Example
  1. package demo;
  2. public class Demo {
  3. public static void main(String args[]) {
  4. String r = "ROLL NO";
  5. int i = 12345;
  6. System.out.printf("%s %15d %n", r, i);
  7. }
  8. }
Output
integer formatting
Example
  1. package demo;
  2. public class Demo {
  3. public static void main(String args[]) {
  4. int r = 54321;
  5. int i = 12345;
  6. System.out.printf("%015d %15d %n", r, i);
  7. }
  8. }
Output
integer formatting with zeroes

Floating Point Number Formatting

  • "%f" Format a string with the required numbers. It will always give six decimal places.
  • "%.3f" Format a string with the required numbers. It gives three decimal places.
  • "%12.3f" Format a string with the required numbers. The string occupies twelve characters. If numbers are not adequate then spaces are used on the left side of the numbers.
Example
  1. package demo;
  2. public class Demo {
  3. public static void main(String args[]) {
  4. System.out.printf("%.3f %n", 123.45789);
  5. }
  6. }
Output
floating point no. formatting
Example
  1. package demo;
  2. public class Demo {
  3. public static void main(String args[]) {
  4. System.out.printf("%12.3f %n", 123.45789);
  5. }
  6. }
Output
floating point no. formatting with spaces

Summary

This article explains string formatting in Java and the use of the printf command in Java.