×

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

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.