devxlogo

Formatting Output in Java

Formatting Output in Java

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();      stringFormatter.proceed();   }   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      scanner.close();   }}/*

Expected output:

[root@mypc]# java StringFormatterHi        : falsethere,    : falseis        : falseit        : truetrue      : falsethat      : falseyou       : falseare       : falsecoming    : falsehome      : falsetoday?    : false*/
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist