OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 1 : Formatted output with printf() Method

 

1.2.1   Formatted Output with printf() Method

In Java, the formatting of output may be carried out in two ways:

·       By using class Formatter

·       By method printf()

The formatter class is discussed later. Now we discuss the printf method that has been adapted by Java from programming language C and modified and upgraded.

Examples:

System.out.printf(“Price of this item is ”,22,“Rupees”);

 System.out.printf(“%d %f\t%c %s \n”, n, x, ch. str);

System.out.printf(“%X \n”, 163);

   System.out.printf(“%o \n”, 163);

Formatting Output of Integer Numbers

Field width and left and right justification the field width is set by integer number placed between % sign and conversion character. The default justification is the right justification. For making it left justification, we place – sign after the % sign and before the field width number.

int p = 73;

System.out.printf(“%d \n”,p);

System.out.printf(“|%20d|\n”,p);

System.out.printf(“|%-20d|\n,p);

Output for the above statements:

73

|              73|

|73              |

Formatting Output of Floating Point Numbers

The following of floating point numbers involve the following three parameters:

·       Field width: It is specified by an integer value between the % sign and the conversion letter f or F

·       Justification: Right justification is default. The left justification is achieved by a negative sign after % sign.

·       Precision: The number of digits after the decimal point is specified by introducing a period followed by a number after % symbol. For example, .3 specifies three digits after the decimal point.

Comments

Popular posts from this blog

How to Get a Job in Top IT MNCs (TCS, Infosys, Wipro, Google, etc.) – Step-by-Step Guide for B.Tech Final Year Students

Common HR Interview Questions

How to Get an Internship in a MNC