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");
public class Demo {
public static void main(String[] args) {
System.out.printf("%s", "Hello");
}
}
You can run your code online here
This one will change String into uppercase
System.out.printf("%S", "Hello");
public class Demo {
public static void main(String[] args) {
System.out.printf("%S", "Hello");
}
}
You can run your code online here
*In this example I have used - flag *
public class Demo {
public static void main(String[] args) {
System.out.printf("'%-10s'", "Hello");
}
}
You can run your code online here
Character Formatting
System.out.printf("%c", "e");
public class Demo {
public static void main(String[] args) {
System.out.printf("%c", 'e');
}
}
You can run your code online here
This one will change character into uppercase
System.out.printf("%C", "e");
public class Demo {
public static void main(String[] args) {
System.out.printf("%C", 'e');
}
}
You can run your code online here
Number Formatting
System.out.printf("%d", 10005);
public class Demo {
public static void main(String[] args) {
System.out.printf("%d", 10005);
}
}
You can run your code online here
In this example we will use locale for a thousand separator
System.out.printf(Locale.US, "%,d %n", 100500);
import java.util.Locale;
public class Demo {
public static void main(String[] args) {
System.out.printf(Locale.US, "%,d %n", 100500);
}
}
You can run your code online here
System.out.printf("%f", 55.1458);
public class Demo {
public static void main(String[] args) {
System.out.printf("%f", 55.1458);
}
}
You can run your code online here
In this example we will reduce the length of decimal part
System.out.printf("%.3f", 55.1458);
public class Demo {
public static void main(String[] args) {
System.out.printf("%.3f", 55.1458);
}
}
You can run your code online here
Date and Time Formatting
System.out.printf("%tT", date);
import java.util.Date;
public class Demo {
public static void main(String[] args) {
Date date = new Date();
System.out.printf("%tT", date);
}
}
You can run your code online here
In this example we will print Hours, Minutes and Seconds separately
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
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);
}
}
You can run your code online here
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);
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);
}
}
You can run your code online here
Boolean Formatting
System.out.printf("%b", 5<4);
public class Demo {
public static void main(String[] args) {
System.out.printf("%b", 5<4);
}
}
You can run your code online here
In this example we will print output in uppercase
System.out.printf("%B", 5<4);
public class Demo {
public static void main(String[] args) {
System.out.printf("%B", 5<4);
}
}
You can run your code online here
New Line
System.out.printf("This%nline%nwill%nbreak");
public class Demo {
public static void main(String[] args) {
System.out.printf("This%nline%nwill%nbreak");
}
}
You can run your code online here
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("================================");
}
}
You can run your code online here
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("================================");
}
}
You can run your code online here
Top comments (2)
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!
what is an
output stream
? and how do the methods know to output to the console?