Introduction

The println() method from PrintStream grade is mainly used for printing in Coffee but there are another methods as well that tin be used for printing. The method y'all use depends on what blazon of output y'all want. In this article, nosotros will be discussing another very useful printing method in Coffee chosen printf and how information technology can be used for formatting.

Java printf method

The printf method in Java can be used to output a formatted string to the console using various format specifiers. It is as well an overloaded method of the PrintStream form. The printf method behaves the aforementioned as the invocation of the format() method.

Java Developer Jobs

Syntax of printf in Coffee

Following are the syntaxes available for overloading the printf method in Coffee.

Whatsoever i of these overloaded methods can be used to format the output:

System.out.printf(cord); Organisation.out.printf(format, arguments); System.out.printf(locale, format, arguments);

The method returns the output stream and it accepts upwardly to three parameters depending on the overloading. The cord parameter is simple every bit the printIn() method. The second line would be used to format the output where the argument would exist the string that we want to format and the format parameter determines the format.

Format specifiers

We specify the format specifiers using theformat parameter. The Format parameter is the combination of literals and format specifiers, e'er starting with the '%' graphic symbol.

Following the '%' sign, a format specifier includes flags, width, precision, and conversion characters in the sequence mentioned below:

%<flags><width><.precision>conversion-graphic symbol

Although, all the specifiers mentioned in the brackets are optional. Most unremarkably a format specifier consists of % accompanied with a conversion character.

  • A conversion character determines how the argument will be formatted.
  • The <flags> ascertain the standard ways for modifying the output. These are most common for formatting integers and floating-signal numbers.
  • The <width> specifies the length of the field for press the statement. Information technology represents the minimum number of characters to be printed.
  • The <.precision> specifies the number of digits of precision when printing a floating-bespeak value. It can also exist used to define the length of a substring from a cord.

Following are some of the most commonly used specifiers in the printf method in Coffee:

Specifier Explanation
%c Format characters
%d Format decimal (integer) numbers (base 10)
%e Format exponential floating-signal numbers
%f Format floating-point numbers
%i Format integers (base of operations 10)
%o Format octal numbers (base 8)
%s Format string of characters
%u Format unsigned decimal (integer) numbers
%x Format numbers in hexadecimal (base sixteen)
%due north add a new line character

Formatting a Boolean value

To format Boolean values, we apply the%b format specifier.  Information technology works in such a manner that if the argument is cipher, then the output will be "false". If an argument is a Boolean value, then the output will the Boolean value already assign to it. Else, the output will be "truthful".

See this example lawmaking:

1.  public static void principal(String[] args) {                      two.    boolean developed = true;  3.    boolean fellow member = false 4.    Arrangement.out.printf("%b%n", adult); 5.    System.out.printf("%b%n", cypher); half dozen.    System.out.printf("%b%n", "random text"); seven.    Organisation.out.printf("%b%n", fellow member); 8. }

The output will be:

truthful faux truthful imitation

Formatting a string

When it comes to formatting strings using printf in Java, we have the%south specifier. Information technology is usually combined with other specifiers depending on the formatting requirements. There are more things yous can practice with %s like using '%s' to put the argument in single quotations or y'all tin brand the argument string uppercase, merely by using the capital letter 'South' in %S.

Run into this code snippet:

System.out.printf("%southward%north", "hullo world!"); Arrangement.out.printf("'%Southward' %n", "hello world!");

And the output volition be:

hello world! 'Hello WORLD!'

The optional specifiers that include width, flag, and precision tin can also be used for formatting the string. To specify a minimum length, nosotros can specify the length of the string using the width specifier. The blank spaces will be added to the left of the string if the argument cord length is less than the minimum length.

Organisation.out.printf("'%10s' %northward", "Hello");

Which gives usa:

          '  Hello'

If you demand to left-justify the string, the flag tin can be used with a -ve sign similar this:

Arrangement.out.printf ("'%-10s' %n", "Hullo");

This will be the output:

'Hello     '

Lastly, you can as well limit the number of characters in the statement cord by specifying aprecision, If we consider the syntax, %x.ys, The number x defines the padding on the left andy is the number of characters in the string.

For example:

System.out.printf("'%3.5s'", "Hello World!");

The output will be:

'   How-do-you-do'

Formatting numbers using Java printf

· Formatting Integers

The Coffee printf method can be used to format all types of integers available in Java which includes, byte, short, int, long, and BigInteger with the utilize of %d specifier.

System.out.printf("it is an integer: %d%n", 10000);

With the assist of thed grapheme, nosotros'll have this result:

it is an integer: 10000

Just similar in string formatting, the flag specifier tin can be used for integers formatting and the output can also be formatted for different locales by overloading the method with the local parameter.

For example:

Arrangement.out.printf(Locale.U.s.a., "%,d %north", 12300); Organization.out.printf(Locale.ITALY, "%,d %n", 10000);

Output:

12,300 10.000

It is to be noted that despite using the ',' with Italy format y'all will still see the '.' Separator based on the locale value.

· Formatting floating numbers and doubles

To format a float number, you have to employ the %f specifier.

Run into this line of code:

Organization.out.printf("%f%n", 3.1423);

which will output:

3.142300

Every bit you can see, the number of decimal places by default is always half-dozen decimal places.

But it tin be formatted by using theprecision specifier like this:

System.out.printf("'%3.2f'%due north", 3.1423);

Now the minimum width of our floating number will exist three, and the length of the decimal part will be two so the output will be:

'three.15'

To take your output in form of scientific annotation, you can utilize the 'e' conversion grapheme:

System.out.printf("'%3.2e'%north", three.1423);

And this will be the output:

'3.15e+00'

Date and time formatting

Java printf method deals with appointment, time, and date-time values for Date/time formatting. The conversion characters consist of 2 characters: thet/T character accompanied with the conversion suffix.

· Formatting time

For formatting fourth dimension using Java Printf, H, Chiliad, and Southward characters are used for extracting the hours, minutes, and seconds from the input Date value. L and N characters correspond the time in milliseconds and nanoseconds accordingly. p character is used to add a.grand./p.chiliad. formatting and lastly, z prints out the time-zone offset.

The data type variable consists of the consummate data and fourth dimension. The time formatting is used to output the time function from the Appointment in different formats.

Meet this code snippet below:

1.Engagement engagement = new Engagement(); ii.System.out.printf("%tT%n", date);

These lines of lawmaking will give the following output:

12:14:46

This is a elementary format for time only if yous need to farther change the format, dissimilar time segments tin also be extracted separately using the characters mentioned earlier,

System.out.printf("hours: %tH%n minutes: %tM%n seconds: %tS%n", date, date, date);

The output will be:

hours: thirteen minutes: 51 seconds: 15

· Formatting dates

Similar to time formatting, there are some special formatting characters used for formatting dates:

Characters Usage
A prints out the full day of the week.
d formats a two-digit twenty-four hour period of the month.
B Prints the total month proper name.
thousand formats a two-digit month.
Y outputs the year in four digits.
y outputs the last two digits of the year.

Using these characters, this line of code:

Organization.out.printf("%1$tA, %one$tB %ane$tY %north", date);

Will output the engagement similar this:

Monday, June 2021

And to have your date in fully numeric format, separated with a '-', you can write your code like this:

Arrangement.out.printf("%1$td-%1$tm-%1$ty %north", engagement);

And the output will exist:

13-06-21

Yous can play around with these characters, and by applying different combinations, hands output a unique date format using any separator of your choice.

See Likewise: A Guide To The Static Keyword In Coffee

Wrapping upward

We discussed how to use the printf method in Java to format date/fourth dimension, strings, numbers, and boolean values to exist printed. At that place is a list of possible options made available in Coffee so that developers tin can easily format the output based on their needs and requirements of the programme. It would somewhen help Java developers in making their program more friendly and user-friendly for finish-users.