printf() in Java
Tags: java, beginners, discuss, javascript
Published: 2021-08-01 15:25:11

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

```Java
System.out.printf("%s", "Hello");
``` 

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%s", "Hello");
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%s.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627821632760/dXdemSCu0.png)

**This one will change String into uppercase**
```Java
System.out.printf("%S", "Hello");
``` 

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%S", "Hello");
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%S (2).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627821887125/prxw3Oatu.png)

**In this example I have used - flag **

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("'%-10s'", "Hello");
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%S1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627824969648/FRH9SjfR_.png)

### Character Formatting

```Java
System.out.printf("%c", "e");
``` 

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%c", 'e');
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%c.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627822159623/GYLp5ElVm.png)

**This one will change character into uppercase**
```Java
System.out.printf("%C", "e");
``` 

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%C", 'e');
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%C (2).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627822349303/EJ3nO5En6.png)

### Number Formatting


```Java
System.out.printf("%d", 10005);
``` 

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%d", 10005);
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***
![java-printf-%d.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627826943470/C47bg2ZB7.png)

**In this example we will use locale for a thousand separator**

```Java
System.out.printf(Locale.US, "%,d %n", 100500);
``` 

```Java
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](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%d-locale.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627827261083/3r_wsWeRy.png)


```Java
System.out.printf("%f", 55.1458);
```

``` Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%f", 55.1458);
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%f.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627827632841/lR-DiCoZv.png)

**In this example we will reduce the length of decimal part**

```Java
System.out.printf("%.3f", 55.1458);
```

``` Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%.3f", 55.1458);
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%f-1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627827820709/gs6H5T4Ue.png)

### Date and Time Formatting

```Java
System.out.printf("%tT", date);
``` 

```Java
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](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%tT.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627828293831/dkuAybro1.png)

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

```Java
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
``` 

```Java
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](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%tH.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627828423519/6-nhiJY1N.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.**

```Java
System.out.printf("%1$tA, %1$tB %1$tY %n", date);
``` 

```Java
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](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%t$A.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627828893914/mFhC6ztb6.png)

### Boolean Formatting

```Java
System.out.printf("%b", 5<4);
``` 

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%b", 5<4);
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%b.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627829110194/bC9LO3i5F.png)

**In this example we will print output in uppercase**

```Java
System.out.printf("%B", 5<4);
``` 

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("%B", 5<4);
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%B (2).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627829233603/Z9yI_uW9N.png)

### New Line 

```Java
System.out.printf("This%nline%nwill%nbreak");
``` 

```Java
public class Demo {
   public static void main(String[] args) {
      System.out.printf("This%nline%nwill%nbreak");
   }
}
``` 
***You can run your code online [here](https://www.tutorialspoint.com/compile_java_online.php)***

![java-printf-%n.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627829470240/E0MPHNmt0.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()


```Java
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](https://www.tutorialspoint.com/compile_java_online.php)***
![java-printf-prob.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627830783011/q80wPz0dF.png)

#### Solution without using printf()

```Java
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](https://www.tutorialspoint.com/compile_java_online.php)***
![java-printf-prob1-sol2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627831402921/g3dAksorY.png)


### Here are few more formattings

![java-printf-yt1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627829855967/ZZ5MePQ4T.png)

![java-printf-yt2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627829861476/EvJDjDSs2.png)

![java-printf-yt3.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627829867503/MYXG5_Wqt.png)

![java-printf-yt4.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627829872753/u2SVTccWI.png)

#### Resources-
*[Video](https://www.youtube.com/watch?v=moQ3Kr8ouiU&t=4s)* ||
*[pdf](https://www.cs.colostate.edu/~cs160/.Summer16/resources/Java_printf_method_quick_reference.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](https://twitter.com/rajatgour20)***
#### *Connect with me on [Twitter](https://twitter.com/ritvikdubey27?s=09) or [LinkedIn](https://www.linkedin.com/in/ritvik-dubey-3bbb22169)*
#### *My personal blog [blog.ritvikdubey.com](https://blog.ritvikdubey.com/)*