Javatpoint Logo
Javatpoint Logo

Java Output Formatting

At times we want the output of a program to be printed in a given specific format. In the C programming language this is possible using the printf( ) function. In this section, we will discuss the different output formatting.

Let's discuss how we can format the output in Java.

There are two methods that can be used to format the output in Java:

  • Using the printf( ) Method
  • Using the format( ) Method

Formatting output using System.out.printf( ) Method

The implementation of this method is very easy as it is similar to the printf( ) function in C programming.

FormattedOutput1.java

Output:

Printing the String value :  JavaTpoint  
 Printing the integer value : x = 512 
 Printing the decimal value : 5.254124 
 Formatting the output to specific width : n = 5.2541 
 Formatted the output with precision : PI = 5.25 
 Formatted to right margin : n = 5.2541 

System.out.format( ) is equivalent to printf( ) and can also be used.

An important point to note is that System.out.print( ) and System.out.println( ) take a single argument, but the printf( ) method can accept multiple arguments.

Formatting Using the DecimalFormat Class:

DecimalFormat is used to format decimal numbers.

FormattedOutput2.java

Output:

 The number is : 123.456700 
 Without fraction part the number is :  123 
 Formatted number with the specified precision is =  123.46 
 Appending the zeroes to the right of the number =  123.456700 
 Appending the zeroes to the left of the number =  00123.46 
 Your Formatted Income in Dollars :  $550,000.79 

Java String Format Specifiers

Here, we are providing a table of format specifiers supported by the Java String.

Format Specifier Data Type Output
%a floating point ( except BigDecima l) Returns Hex output of floating-point number.
%b Any type " true " if non-null, " false " if null
%c Character Unicode character
%d integer ( incl. byte, short, int, long, bigint ) Decimal Integer
%e floating point Decimal number in scientific notation
%f floating point Decimal number
%g floating point Decimal number, possibly in scientific notation depending on the precision and value.
%h any type Hex String of value from hashCode( ) method.
%n None Platform-specific line separator.
%o integer ( incl. byte, short, int, long, bigint ) Octal number
%s any type String value
%t Date/Time ( incl. long, Calendar, Date and TemporalAccessor ) %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer ( incl. byte, short, int, long, bigint ) Hex string.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA