» » Format text using printf() method in java

printf method in java:

  • Print() and println() methods are used to print text and object values or format data.
  • In order to format text we also have printf() method in java
  • Formatting data means displaying corresponding data type value. 
  • For example when print float ot double value if we want to specify upto 2 decimal numbers we user.
  • System.out.printf("%.2f", variable); 
  • Also alignment of string data. when we are printing string data in java using print() and pintf() 



#1. Write a program to print string using print() and printf() methods


  1. package printfinjava;
  2. /**
  3.  * How to format text using java printf() method
  4.  * @author www.instanceofjava.com
  5.  */
  6.  
  7. public class PrintfMethod {
  8.  
  9.     public static void main(String[] args) {
  10.         String str="java printf double";
  11.         
  12.         System.out.println ("String is "+str);
  13.         System.out.printf ("String is %s", str);
  14.  
  15.     }
  16.  
  17. }
Output:

  1. String is java printf double
  2. String is java printf double

java printf table



printf in java double int string


Format double using printf():
  • We can format double using printf() method in java
  • format double to 2 decimal places in java possible by using system.out.printf() method.

#2. Write a program to print double to 2 decimal places in java

  1. package printfinjava;
  2. /**
  3.  * How to format text using java printf() method
  4.  * @author www.instanceofjava.com
  5.  */
  6.  
  7. public class PrintfMethod {
  8.  
  9. public static void main(String[] args) {
  10.  
  11.      double value=12.239344;
  12.      System.out.printf("%.2f", value);
  13.  
  14. }
  15.  
  16. }
Output:

  1. 12.24

#3. Write a program to format text using printf() method in java


printf in java double

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu