Friday, 19 August 2022

Displaying output using printf() and format() in java

To format and display the output, printf() method is available in PrintStream class. This method works similar to printf() function in C. We know that System.out returns PrintStream class object, so to call the printf() method, we can use: System.out.printf(). It uses different format specifiers similar to C language.

If we want only a string that consist of formatted output, then we can take the help of format() of string class. The format characters supported by System.out.printf() are also usable with format() method.

The following program show how these methods works.
class OutputDemo 
{
	public static void main(String[] args) 
	{
		int id=10;
		String name="Raju";
		char ch ='D';
		System.out.printf("id=%d%nname=%s%ninitial=%c",id,name,ch);
		System.out.println("\n Formatted output");
		String str = String.format("id=%d%nname=%s%ninitial=%c",id,name,ch);
		System.out.println(str);
	}
}


Output:



0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top