DEV Community

Cover image for printf() in Java
Ritvik Dubey
Ritvik Dubey

Posted on

printf() in Java

Hello People👋 I hope you are doing well. Yes so you have read the title of the article, printf() in Java, I have recently came across this method, I did some research about this and thought to write about it. So this is gonna be interesting as well as useful for competitive programming. This is actually a part of formatting in java.

Let's begin...

What is formatting

You all know there are two methods println and print to print standard output, but in java.io package there is this class PrintStream which has two formatting methods format and printf, these both methods can be used to replace print and println methods. Both these methods, fromat and printf are equivalent to one another. Both of these methods gives you more control over your print output when numbers are included in your output, soon you'll understand it better. In this article we will talk about printf only.

System.out.printf()

So now you already know this method is part of the java.io.PrintStream class, this method provides String formatting similar to the printf() function in C language. It is also an overloaded method of the PrintStream class. The method returns the output stream and it accepts up to three parameters depending on the overloading.

Let's first look at its syntax:-

System.out.printf(string); (the string parameter is simple as the printIn() method)

System.out.printf(format, arguments);

System.out.printf(locale, format, arguments);

Format

To specify the formatting rules we use the format parameter. This string is composed of literals and format specifiers. Rules start with the % character. Arguments are required only if there are format specifiers in the format string. Format specifiers include flags, width, precision, and conversion characters in the below sequence:-

%[flags][width][.precision]conversion-character

Specifiers in the brackets are optional.

Conversion Characters

  • d : formats decimal integer [byte, short, int, long]
  • f : formats floating-point number [float, double]
  • c : formats character Capital C will uppercase the letter
  • s : formats String Capital S will uppercase all the letters in the string
  • n : adds a new line character
  • t : formats date/time values.

There are many other conversion characters, we will see few more in examples

Flags

The [flags] define standard ways to modify the output.

  • - : left-justify ( default is to right-justify )
  • + : output a plus ( + ) or minus ( - ) sign for a numerical value
  • 0 : forces numerical values to be zero-padded ( default is blank padding )
  • ** (space)** : display a minus sign if the number is negative or a space if it is positive.

Width

The [width] specifies the field width for outputting the argument. It represents the minimum number of characters to be written to the output.

Precision

The [.precision] specifies the number of digits of precision or the length of a substring to extract from a String. Numbers are rounded to the specified precision.

Examples

String Formatting

System.out.printf("%s", "Hello");
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%s", "Hello");
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%s.png

This one will change String into uppercase

System.out.printf("%S", "Hello");
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%S", "Hello");
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%S (2).png

*In this example I have used - flag *

public class Demo {
   public static void main(String[] args) {
      System.out.printf("'%-10s'", "Hello");
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%S1.png

Character Formatting

System.out.printf("%c", "e");
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%c", 'e');
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%c.png

This one will change character into uppercase

System.out.printf("%C", "e");
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%C", 'e');
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%C (2).png

Number Formatting

System.out.printf("%d", 10005);
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%d", 10005);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here
java-printf-%d.png

In this example we will use locale for a thousand separator

System.out.printf(Locale.US, "%,d %n", 100500);
Enter fullscreen mode Exit fullscreen mode
import java.util.Locale;

public class Demo {
   public static void main(String[] args) {
      System.out.printf(Locale.US, "%,d %n", 100500);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%d-locale.png

System.out.printf("%f", 55.1458);
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%f", 55.1458);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%f.png

In this example we will reduce the length of decimal part

System.out.printf("%.3f", 55.1458);
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%.3f", 55.1458);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%f-1.png

Date and Time Formatting

System.out.printf("%tT", date);
Enter fullscreen mode Exit fullscreen mode
import java.util.Date;

public class Demo {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.printf("%tT", date);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%tT.png

In this example we will print Hours, Minutes and Seconds separately

System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
Enter fullscreen mode Exit fullscreen mode
import java.util.Date;

public class Demo {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%tH.png

In this example we will print full day of the week using A, full month name using B and year in four digits using Y.

System.out.printf("%1$tA, %1$tB %1$tY %n", date);
Enter fullscreen mode Exit fullscreen mode
import java.util.Date;

public class Demo {
   public static void main(String[] args) {
      Date date = new Date();
      System.out.printf("%1$tA, %1$tB %1$tY", date);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%t$A.png

Boolean Formatting

System.out.printf("%b", 5<4);
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%b", 5<4);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%b.png

In this example we will print output in uppercase

System.out.printf("%B", 5<4);
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%B", 5<4);
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%B (2).png

New Line

System.out.printf("This%nline%nwill%nbreak");
Enter fullscreen mode Exit fullscreen mode
public class Demo {
   public static void main(String[] args) {
      System.out.printf("This%nline%nwill%nbreak");
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here

java-printf-%n.png

Here is the problem where I found printf() very useful -

In each line of output there should be two columns:
The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.

Solution using printf()

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("================================");
        for(int i=0;i<3;i++)
        {
            String s1=sc.next();
            int x=sc.nextInt();
            System.out.printf("%-15s%03d%n", s1, x); //
        }
        System.out.println("================================");
    }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here
java-printf-prob.png

Solution without using printf()

import java.util.Scanner;

public class Demo {
   public static void main(String[] args) {
      Scanner sc=new Scanner(System.in);
      System.out.println("================================");
      for(int i=0;i<3;i++){
         String s1=sc.next();
         int x = sc.nextInt();
         String newX = "";
         if(x>=0 && x<=9) {
            newX = "00";
         }
         else if(x>=10 && x<=99) {
            newX = "0";
         }
         else {
            newX = "";
         }
         int ct = s1.length();
         int space = 15 - ct;
         String bspc = "";
         for(int j=0; j<=space-1; j++) {
            bspc = bspc +" ";
         }
         System.out.println(s1 + bspc + newX+x);
      }
      System.out.println("================================");
   }
}
Enter fullscreen mode Exit fullscreen mode

You can run your code online here
java-printf-prob1-sol2.png

Here are few more formattings

java-printf-yt1.png

java-printf-yt2.png

java-printf-yt3.png

java-printf-yt4.png

Resources-

Video ||
pdf

Okay so that's enough for now follow my this journey to learn more about Java.

Thank you for reading.

Please share your thoughts about it and correct me if I'm wrong.

I hope you liked it and found it helpful.

Cover:- Rajat Gour

Connect with me on Twitter or LinkedIn

My personal blog blog.ritvikdubey.com

Top comments (2)

Collapse
 
aartiyadav profile image
Aarti Yadav

Hey yesterday I was searching online java compiler to run the code for replace method in java and found this new compiler tool interviewbit.com/online-java-compi... Hope so you also like it!

Collapse
 
theplebdev profile image
Tristan Elliott

what is an output stream ? and how do the methods know to output to the console?