Thursday, February 2, 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
September 13, 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 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 which 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 primarily based 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. Go 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 method 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 primary(String[] args) 
    String identify = "Cameron";
    String web site = "TechTarget";
    System.out.printf("I just like the stuff %s writes on %S. %n", identify, web site);
    /* 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 straightforward Java printf instance gives three vital takeaways:

  • The %s printf specifier doesn’t change letter casing.
  • The %S printf specifier modifications 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?

Whenever you format a String with Java printf, you need to use %n rather than n to specify a line break.

What’s the commonplace Java printf syntax?

The format of the Java printf conversion specifiers all the time 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 smart is the minus signal ( - ). This codecs textual content to the left if the variety of characters exceeds the width setting.

A lot of the Java printf flags are meant 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 damaging or constructive signal
  ( Locations damaging 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 damaging 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.
bundle com.mcnz.printf.instance;

public class JavaPrintfInteger 
  /* Format integer output with Java printf */
  public static void primary(String[] args) 
    int  above = -98765;
    lengthy under =  54321L;
    System.out.printf("%,d :: %d", above, under);
    /* 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 how one can 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 how one can 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 primary(String[] args) 
    double prime    = 1234.12345;
    float  backside = 1234.12345f;
    System.out.printf("%+,.3f :: %,.5f", prime, 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 3 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, equivalent to a Java int, lengthy, quick or byte
  %o  Octal quantity
  %x  Hexadecimal quantity
  %%  Proportion 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.

bundle com.mcnz.scientific.notation;

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

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

FormatFlagsConversionMismatchException

You should definitely 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 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.

For those who 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 primary(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 by 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 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 how one can 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 sophisticated textual content information 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 methodology can generate information 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", "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 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.

Be taught the basics of the Java printf assertion, and you’ll save quite a lot 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

Java :Full Stack Developer – Western Cape saon_careerjunctionza_state

UPB Java Jam brings coffeehouse vibes to Taylor Down Under | Culture

Oracle Java Price Hike Could Be an Opportunity for OpenJDK Vendors

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Java :Full Stack Developer – Western Cape saon_careerjunctionza_state

by learningcode_x1mckf
February 2, 2023
0
Java :Full Stack Developer – Western Cape saon_careerjunctionza_state

I’m on the lookout for a self-driven and longing for fixed self-improvement, gifted particular person to search out and be a part of their ” tribe”. On the...

Read more

UPB Java Jam brings coffeehouse vibes to Taylor Down Under | Culture

by learningcode_x1mckf
February 2, 2023
0
UPB Java Jam brings coffeehouse vibes to Taylor Down Under | Culture

The sound of acoustic guitar, delicate singing and the sturdy scent of heat espresso crammed the area of Taylor Down Beneath (TDU). Throughout the room, many individuals studied...

Read more

Oracle Java Price Hike Could Be an Opportunity for OpenJDK Vendors

by learningcode_x1mckf
February 1, 2023
0
Oracle Java Price Hike Could Be an Opportunity for OpenJDK Vendors

Inflation is rising the price of residing and doing enterprise world wide. The newest merchandise to extend in worth seems to be an Oracle Java SE subscription. Java...

Read more

Full Stack Java Developer ZN

by learningcode_x1mckf
February 1, 2023
0
Full Stack Java Developer ZN

Calling Intermediate and Senior Full Stack Java Builders! Quite a few, game-changing roles with world knowledgeable of their discipline. Modern, Agile … folks such as you .. a...

Read more

Unleash Your Coding Potential: Dive into the World of Java Syntax | by Arslan Mirza | Medium

by learningcode_x1mckf
February 1, 2023
0
Unleash Your Coding Potential: Dive into the World of Java Syntax | by Arslan Mirza | Medium

Information to Java Syntax!https://creator.nightcafe.studio/creation/pYILFuVnvg0CSMHYAUOxJava is the beating coronary heart of the digital world!From smartphones and gaming consoles to enterprise purposes and cloud computing, Java is in every single...

Read more
Next Post
How to use inner shadows to simulate depth with SwiftUI and Core Motion – Hacking with Swift

What’s new in SwiftUI for iOS 15 – Hacking with Swift

Leave a Reply Cancel reply

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

Related News

How to Fetch Data in Javascript like a Pro

How to Fetch Data in Javascript like a Pro

October 15, 2022
Using the Terminal on Linux – Real Python

Using the Terminal on Linux – Real Python

January 31, 2023
Building A Bitcoin Sentiment Analyzer Based On Twitter In Java

Building A Bitcoin Sentiment Analyzer Based On Twitter In Java

January 13, 2023

Browse by Category

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

RECENT POSTS

  • Java :Full Stack Developer – Western Cape saon_careerjunctionza_state
  • Pay What You Want for this Learn to Code JavaScript Certification Bundle
  • UPB Java Jam brings coffeehouse vibes to Taylor Down Under | Culture

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?