Sunday, March 26, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Java

How to use Java printf to format output

learningcode_x1mckf by learningcode_x1mckf
November 7, 2022
in Java
0
How to use Java printf to format output
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


What’s Java printf?

The Java printf perform helps simplify the duty of printing formatted output to the console, terminal window or log information.

The Java printf perform makes it simpler to create informative strings of textual content with out utilizing String concatenation, or counting on non-standard characters that may set off output errors.

In Java, printf is really useful as a substitute for calls to the print or println strategies.

How do you format output with Java printf?

To format textual content based mostly output with the Java printf methodology, comply with these steps:

  1. Create a textual content String literal that features variable substitution factors
  2. Use the suitable conversion specifiers the place variable substitution happens
  3. Add extra flags to the conversion specifiers to format for width, padding and annotations
  4. Cross the String to the Java printf methodology and provide corresponding arguments for every conversion specifier

How do you format a String with Java printf?

The simplest strategy to perceive how the Java printf methodology works is to look at a pattern code snippet.

The next Java printf instance codecs a textual content String, and substitutes two variables into the textual content the place the %s and %S conversion specifiers seem:

 

 

public class FormatOutputJavaPrintf 
  /* Easy Java printf String instance. */
  public static void essential(String[] args) 
    String identify = "Cameron";
    String website = "TechTarget";
    System.out.printf("I just like the stuff %s writes on %S. %n", identify, website);
    /* Printf output: I just like the stuff Cameron writes on TECHTARGET. */
  

This Java printf String instance generates the next formatted output:

I just like the articles Cameron writes on TECHTARGET.

This easy Java printf instance supplies three essential takeaways:

  • The %s printf specifier doesn’t change letter casing.
  • The %S printf specifier modifications letter casing to uppercase.
  • The variables have to be listed within the order they’re referenced within the printf String.
Java String printf examples
Sample Information Printf Output 
 '%s'
 Java
 'Java'
 '%15s'
 Java
 '           Java'
 '%-15s '
 Java
 'Java           '
 '%-15S '
 Java
 'JAVA           '

What does %n in Java printf imply?

If you format a String with Java printf, you should utilize %n instead of n to specify a line break.

What’s the customary Java printf syntax?

The format of the Java printf conversion specifiers at all times follows the identical sample:

% [flags] [width] [.precision] specifier-character

The flags, width and precision settings are all non-obligatory. Nevertheless, the character specifier should match the info kind of the corresponding argument, or else a formatting error will happen.

With pure textual content Strings, the one flag that is sensible is the minus signal ( - ). This codecs textual content to the left if the variety of characters exceeds the width setting.

Many of the Java printf flags are supposed to be used with integers and floating level numbers.

Java printf format flags
printf flag Objective
  – Aligns the formatted printf output to the left
  + The output features a unfavourable or optimistic signal
  ( Locations unfavourable numbers in parenthesis
  0 The formatted printf output is zero padded
   , The formatted output contains grouping separators
 <house> A clean house provides a minus signal for unfavourable numbers and a number one house when optimistic

How do you format an integer with printf in Java?

To format a digit or integer with Java printf:

  • Use %d because the conversion specifier for Base-10 numbers.
  • Precede the letter d with a comma to group numbers by the hundreds.
  • Add an non-obligatory + flag to trigger optimistic numbers to show a optimistic signal.
  • Use the 0 flag to zero-pad the quantity to refill the house specified by the width.
bundle com.mcnz.printf.instance;

public class JavaPrintfInteger 
  /* Format integer output with Java printf */
  public static void essential(String[] args) 
    int  above = -98765;
    lengthy beneath =  54321L;
    System.out.printf("%,d :: %d", above, beneath);
    /* Instance prints: -00098,765 :: +54,321  */
  
Hex, oct and dec integer printf examples
Sample Information Printf output
 ‘%d’  123,457,890
 '123457890'
 ‘%,15d’  123,457,890
 '    123,457,890'
 ‘%+,15d’  123457890
 '   +123,457,890'
 ‘%-+,15d’  123457890
 '+123,457,890   '
 ‘%0,15d’  123457890
 '0000123,457,890'
 ‘%15o’  123457890
 '      726750542'
 ‘%15x’  123457890
'        75bd162'

The next picture exhibits methods to carry out superior Java printf integer formatting:

Java double and float values can simply be formatted and output with Java printf.

How do you format a Java double with printf?

To format a Java float or double with printf, comply with the identical steps to format an integer with the next two addendums:

  1. The conversion specifier for a floating level quantity is %f, not %d.
  2. Use the precision parameter to truncate decimals.

Right here is an easy instance of methods to use Java printf to format floats and double output:

bundle com.mcnz.printf.instance;

public class FloatingPointPrintfExample 
  /* Format float and double output with printf. */
  public static void essential(String[] args) 
    double high    = 1234.12345;
    float  backside = 1234.12345f;
    System.out.printf("%+,.3f :: %,.5f", high, backside);
    /* Instance prints: +1,234.123 :: 1234.12345 */
  

The %+,.3f setting breaks down like this:

  • The plus image + instructs Java printf to incorporate a plus signal if the double is optimistic.
  • The comma instructs Java printf so as to add a thousandths group separator.
  • The .3 instructs Java printf to restrict output to a few decimal locations.
  • %f is the specifier used to format double and floats with printf.
Java printf format specifiers
Printf specifier Information kind
 %s  String of textual content
 %f  floating level worth (float or double)
 %e  Exponential, scientific notation of a float or double
 %b  boolean true or false worth
  %c  Single character char
  %d  Base 10 integer, reminiscent of a Java int, lengthy, quick or byte
  %o  Octal quantity
  %x  Hexadecimal quantity
  %%  Proportion signal
  %n  New line, aka carriage-return
  %tY  12 months to 4 digits
  %tT Time in format of HH:MM:SS ( ie 21:46:30)

Scientific notation in Java with printf

To output a floating level quantity utilizing scientific notation, merely use %e as an alternative of %f to specify the variables.

bundle com.mcnz.scientific.notation;

public class PrintfScientificNotationExample 
  /* Format float and double output with printf. */
  public static void essential(String[] args) 
    double high    = 1234.12345;
    float  backside = 1234.12345f;
    System.out.printf("%+,.3e :: %,.5e", high, backside);
    /* Instance prints: +1.234e+03 :: 1.23412e+03 */
  

Discover how this instance prints out +1.234e+03 :: 1.23412e+03 reasonably than +1,234.123 :: 1234.12345, which is what the previous instance generates.

FormatFlagsConversionMismatchException

Remember to take away any commas within the specifier, as trying so as to add thousandths groupings for scientific notation will lead to a FormatFlagsConversionMismatchException.

Superior double formatting with printf in Java

The next picture demonstrates using varied flags, precision settings and width specifiers to create a desk containing advance formatting of doubles with printf.

Java printf format output

Right here’s the code and output of a desk of Java double printf examples.

How do you format a Java char or boolean with printf?

In Java, a char makes use of the %c specifier. A boolean values makes use of %b.

In the event you use %C or %B is used to format a boolean or char with Java printf, the values are printed in uppercase.

bundle com.mcnz.scientific.notation;

public class PrintfCharBooleanExample 
  /* Boolean char Java printf instance. */
  public static void essential(String[] args) 
    boolean flag = false;
    char coal = 1234.12345f;
    System.out.printf("%B :: %c :: %C", flag, coal, 'u0077');
    /* Instance prints: FALSE :: a :: W */
  

As you’ll be able to see on this instance, the printf assertion not solely codecs char variables, but it surely additionally converts and correctly prints out unicode character numbers.

How do you format a Date in Java with printf?

One of the simplest ways to output date and time values in Java is with the DateTimeFormatter class. However the printf methodology helps easy date formatting via using the %t conversion specifier together with a further date element parameter.

With a java.util.Date object, we will use the next choices:

  • %tH to show the hour
  • %tM to show the minutes
  • %tS to show the seconds
  • %tp to print am or pm
  • %tx for the time-zone offset

Java printf date instance

The next instance codecs the time with printf:

Date d = new Date();
System.out.printf("%tH %tM %tS %tz", d, d, d, d);
/* Outputs: 22 26 49 -0400 */

How do you format native time in Java with printf?

Fashionable applications want to make use of the LocalDateTime object over java.util.Date.

The next parameters are generally used to format DateTime output with Java printf:

  • %tA to printf the day of the week in full
  • %ta to printf the abbreviated day of the week
  • %tB to printf the complete identify of the month
  • %tb to printf the abbreviated month identify
  • %td to printf the day of the month
  • %tY to output all 4 digits of the yr
  • %tY to printf the final two digits of the yr
  • %tp to show am or pm
  • %tL to show the millisecond offset
  • %tz to show the time-zone offset

Java printf time instance

The next Java printf time instance demonstrates methods to format values outlined in a LocalDateTime object:

LocalDateTime dt = LocalDateTime.now();
System.out.printf(" %ta %te, %tY %tT %tp ", dt, dt, dt, dt, dt);
/* Codecs LocalDateTime output as: Sat 6, 2022 21:19:56 pm */ 

This Java time printf instance prints out:
Sat 6, 2022 21:19:56 pm

How do you format a desk with printf?

Typically builders wish to neatly format sophisticated textual content knowledge earlier than it’s printed to the console or a log file.

The Java printf command doesn’t present any built-in options that assist construction output. Nevertheless, inventive use of the Java printf methodology can generate knowledge tables.

For instance, the next code generates a desk that paperwork the properties of the Java primitive varieties:

System.out.printf("--------------------------------%n");
System.out.printf(" Java's Primitive Varieties         %n");
System.out.printf(" (printf desk instance)         %n");

System.out.printf("--------------------------------%n");
System.out.printf("| %-10s | %-8s | %4s |%n", "CATEGORY", "NAME", "BITS");
System.out.printf("--------------------------------%n");

System.out.printf("| %-10s | %-8s | %04d |%n", "Floating", "double",  64);
System.out.printf("| %-10s | %-8s | %04d |%n", "Floating", "float",   32);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "lengthy",    64);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "int",     32);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "char",    16);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "quick",   16);
System.out.printf("| %-10s | %-8s | %04d |%n", "Integral", "byte",    8);
System.out.printf("| %-10s | %-8s | %04d |%n", "Boolean",  "boolean", 1);

System.out.printf("--------------------------------%n");

When the code runs, a tabular output is created.

Table with Java printf example

Create a Java printf desk via the inventive use of width, precision and printf format flags.

Java printf examples

The Java printf assertion enormously simplifies the duty for formatting output generated in a Java program.

Study the basics of the Java printf assertion, and you’ll save a substantial amount of time when producing output for the console, logs and different text-based output streams.

Java printf cheatsheet
Sample Information Printf output
 ‘%s’  Java
 'Java'
 ‘%15s’  Java
 '           Java'
 ‘%-15s ‘  Java
 'Java           '
 ‘%d’  123,457,890
 '123457890'
 ‘%,15d’  123,457,890
 '    123,457,890'
 ‘%+,15d’  123457890
 '   +123,457,890'
 ‘%-+,15d’  123457890
 '+123,457,890   '
 ‘%0,15d’  123457890
 '0000123,457,890'
 ‘%15o’  123457890
 '      726750542'
 ‘%15x’  123457890
'        75bd162'
 ‘%15f’  12345.123450
'   12345.123450'
 ‘%-15.3f’ 12345.123450
'12345.123      '
 ‘%015.3f’  12345.123450
'00000012345.123'
 ‘%e’  12345.123450
'1.234579e+08'
 ‘%.2e’  12345.123450
'1.23e+08'
 ‘%7tH %<-7tM’
new Date()
'     22 35     '
 ‘%15tT’
LocalDateTime.now()
'       22:35:53'

 



Source link

You might also like

2023 Java roadmap for developers – TheServerSide.com

YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students – The Hans India

Disadvantages of Java – TheServerSide.com

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

2023 Java roadmap for developers – TheServerSide.com

by learningcode_x1mckf
March 26, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

2023 Java roadmap for developers  TheServerSide.com Source link

Read more

YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students – The Hans India

by learningcode_x1mckf
March 26, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students  The Hans India Source link

Read more

Disadvantages of Java – TheServerSide.com

by learningcode_x1mckf
March 26, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Disadvantages of Java  TheServerSide.com Source link

Read more

Advantages of Java – TheServerSide.com

by learningcode_x1mckf
March 26, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Advantages of Java  TheServerSide.com Source link

Read more

Java Developer Survey Reveals Increased Need for Java … – Benzinga

by learningcode_x1mckf
March 25, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Java Developer Survey Reveals Increased Need for Java ...  Benzinga Source link

Read more
Next Post
What’s New From October 2022 – Real Python

What's New From October 2022 – Real Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Top C++ Based Data Science And Machine Learning Libraries – MarkTechPost

February 17, 2023
The best coding languages for trading algorithms: Python, C++, Javascript?

The best coding languages for trading algorithms: Python, C++, Javascript?

September 6, 2022
How ‘Java’ Became Coffee’s Nickname and a Programming Language

How ‘Java’ Became Coffee’s Nickname and a Programming Language

December 8, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • 2023 Java roadmap for developers – TheServerSide.com
  • YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students – The Hans India
  • Disadvantages of Java – TheServerSide.com

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?