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.

Find Us On Facebook

Computer Basics

More

C Programming

More

Java Tutorial

More

Data Structures

More

MS Office

More

Database Management

More
Top