The System.out.printf()
function in Java allows users to print formatted data.
Locale
- if not null, the object is formatted according to the norms of the specified regionUsers in France may choose to print the date according to the local practice which involves the use of comma instead of decimal to represent floating point numbers. The syntax for that will be:
Date data = new Date();
System.out.printf(Locale.FRANCE, "Printing current data and time: %tc", data);
Object
- the object(s) to be printed on the screen
String
- the string being passed to the function contains the conversion characters
In order to simplify the formatting process, Java allows programmers to make use of certain keywords to format different data types. Some of the commonly used specifiers are:
Look at the following examples to get a better understanding of how the printf()
function can be used in different situations.
class JavaFormat{public static void main(String args[]){String data = "Hello World!";System.out.printf("Printing a string: %s\n", data);}}
Note: Using the conversion characters in uppercase will print output in uppercase. Notice the change in the following code.
For instance,
%S
will be used to print in upper-case instead of%s
class JavaFormat{public static void main(String args[]){String data = "Hello World!";System.out.printf("Printing a string in uppercase: %S\n", data);}}
class JavaFormat{public static void main(String args[]){int x = 100;System.out.printf("Printing a decimal integer: %d\n", x);}}
class JavaFormat{public static void main(String args[]){float x = 10.9;System.out.printf("Printing a floating point number: x = %d\n", x);}}
import java.util.Date;class JavaFormat{public static void main(String args[]){Date data = new Date();System.out.printf("Printing current data and time: %tc", data);}}
In addition to this, the printf()
function permits users to print multiple objects at the same time.
import java.util.Date;class JavaFormat{public static void main(String args[]){String data = "Hello World!";int x = 9876;Date date = new Date();System.out.printf("Printing multiple data at once: %S %d %tA \n", data,x,date);}}
Free Resources