Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

How to Use the printf() Function in Java

/* This printf() function works as a formatted print function.
Think about the two scenarios given below:

Scenario 1: Your friend Tommy wants you to provide him your
notebook's PDF via an email. You can simply compose an email,
provide a subject as you like (such as, hey Tommy,
it's Fahim). You can also avoid writing anything to the body
part of the email and send that email after attaching the PDF
with the email. As simple as that – you don't need to maintain
any courtesy with your friend, right?

Scenario 2: You couldn't come to your class yesterday.
Your professor asked you to provide the valid reasons with
proof and submit the documents via an email.

Here, you can't mail your professor like you did for you
friend, Tommy. In this case, you need to maintain formality
and proper etiquette. You have to provide a formal and legit
subject and write the necessary information in the body part.
Last but not least, you have to attach your medical records
with your email after renaming them with the proper naming
convention. Here, you formatted your email as the authority
wants!

In the printf()function, we follow the second scenario.
If we want to specify any specific printing format/style,
we use the printf()function.

Let me give you a short example of how this works:
*/



public class Main{
    public static void main(String[] args) {
        double value = 2.3897;
        System.out.println(value);
        System.out.printf("%.2f" , value);
    }
}



/* Here, I am declaring a double type variable named value
and I am assigning 2.3897 to it.
Now when I use the println() function,
it prints the whole value with the 4 digits after the radix
point.

This is the output:
*/


// 2.3897
// 2.39


/* But after that, when I am using the printf() function,
I can modify the output stream of how I want the function to
print the value. Here, I am telling the function that I want
exactly 2 digits to be printed after the radix point.
So the function prints the rounded value up to 2 digits after
the radix point.

In this type of scenario, we normally use the printf()
function. But keep in mind that it has a wide variety of
uses in the Java programming language.
*/
 
PREVIOUS NEXT
Tagged: #How #Use #Function #Java
ADD COMMENT
Topic
Name
1+1 =