How to Use printf, println and print Methods in Java

To display output on terminal, we can use print, println or printf methods (functions) in Java. These methods are available in the static PrintStream object System.out. We will see the use of each method in detail below.

print()

This method displays instance of any data type (Object, int, float, double, String, char etc) on terminal display. If you want to display something in a new line, you have to prefix and/or suffix the new line character with the content. An example is as follows:

int a=600;
System.out.print("\nThis is a line\n");
System.out.print(a);
System.out.print("\n");

The above code displays the first string and the number 600 in two separate lines

println()

Unlike print(), println() method appends a new-line  character to the end of the content. Just like print() method, println() method also has various overloaded definitions so that it could take variable of any type as argument. If the println() method is called without any arguments, it will simply output a new line character. The following code and its output will give you an idea.
System.out.println("Hi this is first line");
System.out.println();
System.out.println("Above this, an empty println() was called");

Output:


Hi this is first line

Above this, an empty println() was called

printf()

The printf() method is similar to the printf() function in stdio.h header in c language. You can use System.out.printf() method to format the srting just as you do in c language. This method writes a formatted string to this output stream using the specified format string and arguments. The usage is as follows:

System.out.format(format, args);

Let us see a few examples:
String s="Shareef";
int number=7343543;
System.out.printf("My name is %s and number is %d",s,number);
System.out.printf("\nThe following is multiplication table of 9:\n");
for(int i=1;i<=10;i++)
    System.out.printf("%2d * %1d = %2d\n",i,9,i*9);

The output of above code is:


My name is Shareef and number is 7343543The following is multiplication table of 9:
 1 * 9 =  9
 2 * 9 = 18
 3 * 9 = 27
 4 * 9 = 36
 5 * 9 = 45
 6 * 9 = 54
 7 * 9 = 63
 8 * 9 = 72
 9 * 9 = 81
10 * 9 = 90

No comments:

Post a Comment