Software Development Training: How to Use Printf() Method in Java

Java Printf() Method Codeflare

If you’ve been on Java programming language for some time, you’ve probably seen System.out.print() and System.out.println(). But there’s also System.out.printf(), and that’s Java’s printf() method.

The Java printf() is used for displaying formatted Strings or outputs. The “f” in the printf() means format.

To properly format outputs in Java, We make use of something called conversion characters. Here’s a list of them:

  • %c character
  • %d decimal (integer) number (base 10)
  • %e exponential floating-point number
  • %f floating-point number (double and float)
  • %i integer (base 10)
  • %o octal number (base 8)
  • %s String
  • %u unsigned decimal (integer) number
  • %x number in hexadecimal (base 16)
  • %t formats date/time
  • %% prints a percent sign
  • %n prints a new line

Now let’s print out a simple statement using this method

Public class PrintFormat(){
public static void main (String args[]){
String str = "Hello World";
System.out.printf(%s %n, str);
}
}

Result: Hello World!

Now, the %s means that the parameter we are passing is a String, the %n indicates a newline. Also notice that if you make the “s” in the %s a capital letter (i.e., %S), all you result will be printed in uppercase.

Wait … I know what you’re thinking …

“Why go through all these stress just to print out a simple Hello World when a normal System.out.println() would do the trick?”

Wait for it …

Now let’s say we want to print out this number 4.56768 to 2 decimal places. Yeah, gotcha.

Public class PrintFormat(){
public static void main (String args[]){
double myVal = 4.56768;
 System.out.printf("%.2f%n", myVal);
}
}

Result: 4.57

You can also pass the number directly

Public class PrintFormat(){
public static void main (String args[]){
 System.out.printf("%.2f%n", 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280);
}
}

Result: 3.14

So, there you have it guys!

Want to watch some video demonstrations? Here you go

Get personalized one-on-one training on ICT and software development

Software development tutorials Codeflare

Leave a Reply

Your email address will not be published. Required fields are marked *