Saturday, April 1, 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
January 2, 2023
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 operate helps simplify the duty of printing formatted output to the console, terminal window or log recordsdata.

The Java printf operate 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 advisable 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 technique, observe 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. Move the String to the Java printf technique and provide corresponding arguments for every conversion specifier

How do you format a String with Java printf?

The best strategy to perceive how the Java printf technique 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 major(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 gives three vital takeaways:

  • The %s printf specifier doesn’t change letter casing.
  • The %S printf specifier adjustments letter casing to uppercase.
  • The variables should 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 use %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-compulsory. Nonetheless, the character specifier should match the information 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 meant to be used with integers and floating level numbers.

Java printf format flags
printf flag Goal
  – Aligns the formatted printf output to the left
  + The output features a adverse or constructive signal
  ( Locations adverse numbers in parenthesis
  0 The formatted printf output is zero padded
   , The formatted output consists of grouping separators
 <area> A clean area provides a minus signal for adverse numbers and a number one area when constructive

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 1000’s.
  • Add an non-compulsory + flag to trigger constructive numbers to show a constructive signal.
  • Use the 0 flag to zero-pad the quantity to refill the area specified by the width.
package deal com.mcnz.printf.instance;

public class JavaPrintfInteger 
  /* Format integer output with Java printf */
  public static void major(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, observe 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 a straightforward instance of methods to use Java printf to format floats and double output:

package deal com.mcnz.printf.instance;

public class FloatingPointPrintfExample 
  /* Format float and double output with printf. */
  public static void major(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 constructive.
  • 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, corresponding to a Java int, lengthy, brief or byte
  %o  Octal quantity
  %x  Hexadecimal quantity
  %%  Share signal
  %n  New line, aka carriage-return
  %tY  Yr 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.

package deal com.mcnz.scientific.notation;

public class PrintfScientificNotationExample 
  /* Format float and double output with printf. */
  public static void major(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 fairly than +1,234.123 :: 1234.12345, which is what the previous instance generates.

FormatFlagsConversionMismatchException

Make sure you take away any commas within the specifier, as making an attempt 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 numerous 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.

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

package deal com.mcnz.scientific.notation;

public class PrintfCharBooleanExample 
  /* Boolean char Java printf instance. */
  public static void major(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, however it 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 technique helps easy date formatting by using the %t conversion specifier together with a further date element parameter.

With a java.util.Date object, we are able to 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 desire 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 total 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 12 months
  • %tY to printf the final two digits of the 12 months
  • %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?

Generally builders wish to neatly format difficult 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. Nonetheless, inventive use of the Java printf technique can generate knowledge tables.

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

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", "brief",   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 by the inventive use of width, precision and printf format flags.

Java printf examples

The Java printf assertion drastically 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

So why did they decide to call it Java? – InfoWorld

Senior Java Developer – IT-Online

West Java to provide simultaneous polio vaccinations from Apr 3 – ANTARA English

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

So why did they decide to call it Java? – InfoWorld

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

So why did they decide to call it Java?  InfoWorld Source link

Read more

Senior Java Developer – IT-Online

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

Senior Java Developer  IT-On-line Source link

Read more

West Java to provide simultaneous polio vaccinations from Apr 3 – ANTARA English

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

West Java to provide simultaneous polio vaccinations from Apr 3  ANTARA English Source link

Read more

COBOL programming skills gap thwarts modernization to Java – TechTarget

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

COBOL programming skills gap thwarts modernization to Java  TechTarget Source link

Read more

User input with a Java JOptionPane example – TheServerSide.com

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

User input with a Java JOptionPane example  TheServerSide.com Source link

Read more
Next Post
Generative Music Created In Minimalistic Javascript Code

Generative Music Created In Minimalistic Javascript Code

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

Gootloader malware updated with PowerShell, sneaky JavaScript – The Register

February 5, 2023
Indonesia Escapes FIFA Sanction after East Java Crush

Indonesia Escapes FIFA Sanction after East Java Crush

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

4 Packages for Working With Date and Time in JavaScript – MUO – MakeUseOf

April 1, 2023

Browse by Category

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

RECENT POSTS

  • So why did they decide to call it Java? – InfoWorld
  • Senior Java Developer – IT-Online
  • 4 Packages for Working With Date and Time in JavaScript – MUO – MakeUseOf

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?