Site icon TestingDocs.com

Difference between print() and printf() statements

Introduction

In this tutorial, we will look into some differences between print and print statements. We can find these methods in PrintStream class. print method in most cases is used to print strings.

print()

Sample method signature :

public void print(String s)

This method accepts a single value of any of the primitive or reference data types as a parameter and prints the given value as the output of the program.

Ex: int,long,String , Object etc.

Usage:

System.out.print(“String to be printed”);

There is a variation of this method called println(). This method prints and then terminates the current line. The print statements that come after this method print on a new line.

Usage:

System.out.println(“String to be printed”);

printf()

printf() method is used to write a formatted string to the output stream.

public PrintStream printf(String format, Object … args)

Usage:

System.out.printf( “Format-string” [, arg1, arg2, … ] );

Java Program

 

package apache;
//www.TestingDocs.com
//print() and printf() methods demo

public class JavaDemo {

	public static void main(String[] args) {
		String str = "Hello World"; 
		double fmtTwoDecimalsValue=0.072345;
		System.out.println(str);
		System.out.print("Hello ");
		System.out.print("World");
		System.out.println();
		System.out.printf("Value =: %.2f",fmtTwoDecimalsValue);
	}

}

Program Output

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

More information on Java can be found on the official website:

https://www.oracle.com/in/java/

Exit mobile version