×

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will talk about the varied output formatting in this section.

Sometimes printing the output in a specific format is necessary while using competitive programming. In C, the printf function is widely used. Let's talk about formatting the output in Java.

In Java, formatting the output can be done in one of two ways:

  • Making use of the Printf() Method
  • Making use of the format () Method

Output Formatting using System.out.printf() method

Because this Method is identical to the printf() function used in C programming, its implementation is quite simple.

OutputFormatting.java

import java .io .*;


public class JavaCallable  
{  
  public static void main ( String args[ ] )  
  {  
    // Printing the string using the printf method in Java  
    String s = " Hello word " ;  
    System.out.printf( " 
 The String value using printf() : %s 
 ", s ) ;  
    // Printing the Integer using the printf method in Java   
    int i = 45 ;  
    System.out.printf( " 
 The Integer value using printf() : i = %d 
 ", i ) ;  
    // Printing the float using the printf method in Java  
    float f = 8.456f ;  
    System.out.printf( " 
 The float value using printf() : %f 
 ", f ) ;  
    // formatting the float value to a specific decimal number using %.nf in printf  
    System.out.printf( " 
 Formating the float value to specific decimal : f = %.4f 
 ", f ) ;  
    // formatting the float value to a specific decimal number using %.nf in printf  
    System.out.printf( " 
 Formating the float value to two decimal : f = %.2f 
 ", f ) ;  
    // formatting the float value to a specific right margin number using %n.mf in printf  
    System.out.printf( " 
 Formating the float value right margin : n = %20.4f 
 ", f ) ;  
  }  
}  

Output

The String value using printf():  Hello word  
 The Integer value using printf() : i = 45 
 The float value using printf() : 8.456000 
 Formating the float value to a specific decimal: f = 8.4560
 Formating the float value to two decimal: f = 8.46
 Formating the float value right margin : n = 8.4560

printf( ) system.out.format() can also be utilised.

It's vital to remember that, unlike the printf() method, System.out.print() and System.out.println() only accept one parameter.

Output Formatting Using the Decimal Format class

We use the Decimal format class to format the decimal numbers in Java.

import java.text.DecimalFormat ;  
// Importing the Decimal format class    
public class JavaCallable 
{  
  public static void main( String args[ ] )  
  {  
    double num = 987.65432 ;  
    // Displaying the number initialised in the console   
    System.out.printf( " 
 Double number taken is : %f 
 ", num ) ;      
    // Displaying only the integral part of the double number using decimal format   
    DecimalFormat obj = new DecimalFormat( " #### " ) ;  
    System.out.println( " 
 Without fraction part the number is : " + obj.format( num ) ) ;  
    // Displaying only up to the two decimals of the double number using decimal format
    obj = new DecimalFormat( " #.## " ) ;  
    System.out.println( " 
 Double number up to two decimal places is = " + obj.format( num ) ) ;  
    // appending zero to the decimal number on the right side as specified, instead of #, we use the digit 0  
    obj = new DecimalFormat( " #.000000 " ) ;  
    System.out.println( " 
 Adding zeros to the right part of the double number = " + obj.format( num ) ) ;  
    // appending zero to the decimal number on the left side as specified, instead of #, we use the digit 0   
    obj = new DecimalFormat( " 00000.00 " ) ;  
    System.out.println( " 
 Adding zeros to the right part of the double number = "+ obj.format( num ) ) ;  


    // converting rs into dollars using decimal format class  


    double money = 550000.789 ;  


    obj = new DecimalFormat( " $###,###.## "  ) ;  


    System.out.println( " 
 Money after converting in to dollars : " + obj.format( money ) ) ;  


  }  


}  

Output

Double number taken is : 987.654320 
 Without fraction part the number is :  988
 Double number up to two decimal places is =  987.65
 Adding zeros to the right part of the double number =  987.654320
 Adding zeros to the right part of the double number =  00987.65
 Money after converting in to dollars :  $550,000.79

Related Topics

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.