How println,print and printf are different in java?

We use print(), println() and printf() for a common purpose which is printing the text on the screen.

println()  : prints the text and moves to the next line. This most commonly used in java the problem about this is that if you want to print multiple things on same line than we have use String Concatenation which is a bit complicated and tedious.

Example for println() method:

public class Me {
public static void main(String args[]){
System.out.println(“Example of println”);
System.out.println(“codeheaven.wordpress.com”);

}

}

Output: Example of println() method

codeheaven.wordpress.com

As you can see in the output of the example code the text has appeared in the different lines this is due to the println() method.

print() method : It is  similar to println() the only difference is that after printing the text it remains to the same line. It also faces the problems of string concatenation.

Example for print() method:

public class Me {
public static void main(String args[]){
System.out.print(“Example of print function “);
System.out.print(“codeheaven.wordpress.com”);

}

}

Output:   Example of print function codeheaven.wordpress.com

printf() method: This is also used to print text to the screen but this function uses C style string formatting this resolves the problem of String Concatenation. But it is not going to move to the next line after printing for this purpose you need to use \n

Example of printf() function:
public class Me {
public static void main(String args[]){
int a = 10 , b = 20;
System.out.printf(“a: %d b: %d”,a,b);
System.out.print(“codeheaven.wordpress.com”);

}

}

Output : a: 10  b: 20codeheaven.wordpress.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s