Browse DevX
Sign up for e-mail newsletters from DevX


Tip: Formatting Output in Java

Learn how to employ proper formatting for your Java output.


Proper formatting of output is essential. There are times when the details presented are not formatted.

The code snippet below displays details in a formatted manner that is a better presentation.

import java.util.*;

public class StringFormatter {

   public static void main(String args[])
      StringFormatter stringFormatter = new StringFormatter();

   final String stringSentence = "Hi there, is it true that you are coming home today?";
   private void proceed()
      //Creating a Scanner with the string stringSentence
      Scanner scanner = new Scanner(stringSentence);

      //Scanning the string 
      while (scanner.hasNext()) {
         //Formatting the string. The first string will have 10 character spacing, this can be adjusted as needed. 
         //The option -10, 10 will add spaces leading and trailing respectively.
         System.out.println(String.format("%-10s: %s" , scanner.next().toString(), scanner.hasNextBoolean() ));

      //Closing the Scanner


Expected output:

[root@mypc]# java StringFormatter
Hi        : false
there,    : false
is        : false
it        : true
true      : false
that      : false
you       : false
are       : false
coming    : false
home      : false
today?    : false


Visit the DevX Tip Bank


Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date