对象已移动

可在此处找到该文档 Formatting Strings in Java: String.format() Method – New Self New Life
New Self New Life
No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
New Self New Life
No Result
View All Result
Home Softwares

Formatting Strings in Java: String.format() Method

by admin
3 years ago
in Softwares
Working with Regular Expressions in Java
Share on FacebookShare on Twitter


Java Developer Tutorials
Whereas System.out.println() is okay for debugging and displaying easy messages, it isn’t nice for formatting strings. Formatted strings not solely show the string content material however in addition they present the content material in a specified sequence. As an illustration, when displaying massive integers like 100000000, it’s possible you’ll need to embrace commas in order that it seems as 100,000,000. Equally with decimal numbers, you would possibly need to present a selected variety of decimal locations like 199.53 together with rounding. Programmers can be comfortable to know that Java presents a couple of formatting strategies with ample help for a wide range of information varieties like Double, Integer, and Date.

There are three major methods to format a string in Java. You should use the String.format() technique, the printf() technique, or the MessageFormat class for formatting strings. Of those, the String.format() technique is essentially the most generally used, so we can be protecting it on this Java programming tutorial. We are going to get to the opposite two choices in a future article.

Should you want a refresher or missed our earlier tutorial on working with strings in Java, remember to go to: Java Output Fundamentals.

String.format() Technique Syntax in Java

Java’s String.format() is a static technique that returns a formatted String utilizing the given locale, format String, and arguments. It is available in two flavors, as follows:

public static String format(String format, Object... args)
public static String format(Locale locale, String format, Object... args)
  • locale: the locale utilized throughout formatting. Nevertheless, whether it is null the localization shouldn’t be utilized.
  • format: the String to format.
  • args: the parameter referenced by format specifiers within the format String. If the arguments are greater than the format specifiers, the additional arguments are ignored. The variety of arguments can range and could also be omitted fully.

Right here is an instance of the right way to use String.format() in Java:

class StringFormatExample {
  public static void important(String[] args) {
    String title = "Rob Gravelle";
    String str  = String.format("My title is %s", title);
    System.out.println(str); // My title is Rob Gravelle
  }
}

The locale argument is very helpful for formatting numbers and dates based on the principles of a given locale. For instance, here’s a locale worth of “France” that replaces the decimal level with a comma, as per the France quantity system:

import java.util.*;

class StringFormatLocaleExample {
  public static void important(String[] args) {
    System.out.format(
      Locale.FRANCE, 
      "The worth of the float " + "variable is %f  ",
      10.3242342
    ); // The worth of the float variable is 10,324234.
  }
}

String.format() Exceptions in Java

You need to be conscious that the String.format() technique throws a few exceptions:

  • NullPointerException: This exception is thrown if the String argument handed is null.
  • IllegalFormatException: If the format specified is illegitimate or there are inadequate arguments.

Builders nearly by no means catch these exceptions, as they have a tendency to point improper use of the strategy somewhat than some type of anticipated runtime exception.

Learn: Java Instruments to Improve Productiveness

Formatting String Width, Alignment, and Padding in Java

The String.format() technique additionally permits programmers to set the width, alignment, and padding of the formatted String. The next class incorporates examples of every, in addition to varied mixtures:

public class StringFormatWidthAndPaddingExample {
  public static void important(String[] args) 
    System.out.println(greeting);
  
}

Specifying Varieties with String.Format()

As we noticed within the locale argument instance above, String.format() can be used to transform and format different information varieties right into a string. To do this, Java gives a wide range of Format Specifiers. These start with a p.c character (%) and terminate with a typechar “sort character“, which signifies the kind of information (int, float, and many others.) that can be transformed, in addition to the way in which during which the information can be represented (decimal, hexadecimal, and many others.) The total syntax of a Format Specifier in Java is:

% [flags] [width] [.precision] [argsize] typechar

We are able to see in this system under how varied Format Specifiers have an effect on the airing of knowledge:

import java.util.Date;

public class StringFormatTypesExample {
  public static void important(String[] args) {
    String str1 = String.format("%d", 2112); // Integer worth
    String str2 = String.format("%f", 98.7); // Float worth
    String str3 = String.format("%x", 101);  // Hexadecimal worth
    String str4 = String.format("%o", 023);  // Octal worth
    String str5 = String.format("%tc", new Date()); // Date object
    String str6 = String.format("%c", 'Z');  // Char worth
    
    System.out.println(str1); // 2112
    System.out.println(str2); // 98.700000
    System.out.println(str3); // 65
    System.out.println(str4); // 23
    System.out.println(str5); // Thu Jan 05 20:52:06 GMT 2023
    System.out.println(str6); // Z
  }
}

Right here is the total checklist of Format Specifiers for the String.format() technique:

  • %% – Inserts a “%” signal
  • %x/%X – Integer hexadecimal
  • %t/%T – Time and Date
  • %s/%S – String
  • %n – Inserts a newline character
  • %o – Octal integer
  • %f – Decimal floating-point
  • %e/%E – Scientific notation
  • %g – Causes Formatter to make use of both %f or %e, whichever is shorter
  • %h/%H – Hash code of the argument
  • %d – Decimal integer
  • %c – Character
  • %b/%B – Boolean
  • %a/%A – Floating-point hexadecimal

Word that some specifiers could also be both lowercase or uppercase. The case of the specifier dictates the case of the formatted letters. Apart from that, the conversion carried out is similar, no matter case.

Learn: The right way to Concatenate Strings in Java

Argument Index and String.format()

Recall from earlier within the tutorial that String.format() can settle for a number of Objects to format. The Argument Index is an integer indicating the place of the argument in that checklist of Objects. To not be confused with the Numbered Teams of the String substitute() operate ($1, $2, and many others.), Argument Indexes place the quantity BEFORE the greenback signal. Therefore, the primary argument is referenced by 1$, the second by 2$, and so forth. Here’s a program that codecs two items of knowledge: a float and a String:

public class StringFormatArgumentIndexExample {
  public static void important(String[] args) {
    String product = "Bread";
    double value = 4.99;
    
    String str = String.format("The worth of %2$s is CAD $%1$.2f as we speak.", value, product);
    
    // The worth of Bread is CAD $4.99 as we speak.
    System.out.println(str);
  }
}

Closing Ideas on Formatting Strings in Java

Though there are a number of methods to format a string in Java, the String.format() technique is essentially the most generally used as a result of its large versatility. From localization, sort conversion, width, alignment and padding, it’s got you coated!

Learn extra Java programming tutorials and software program growth guides.



Source link

Tags: FormattingJavaMethodStringformatstrings
Previous Post

House of the Dragon’s Emma D’Arcy: 5 Things to Know

Next Post

‘How Do I Know This Place?’

Related Posts

What is Parameter-Efficient Fine-Tuning (PEFT) and Why It Matters
Softwares

What is Parameter-Efficient Fine-Tuning (PEFT) and Why It Matters

by admin
September 29, 2025
Speed Dials with Widgets – Vivaldi Browser snapshot 3820.3
Softwares

Speed Dials with Widgets – Vivaldi Browser snapshot 3820.3

by admin
September 28, 2025
Magento 2 SEO for ChatGPT : The AI Ranking Guide
Softwares

Magento 2 SEO for ChatGPT : The AI Ranking Guide

by admin
September 25, 2025
Microsoft fixes Windows automatic apps rearrangement issue
Softwares

Microsoft offers no-cost Windows 10 lifeline

by admin
September 26, 2025
Syncfusion restructures Essential Studio into multiple different suites to provide greater flexibility for developers
Softwares

Syncfusion restructures Essential Studio into multiple different suites to provide greater flexibility for developers

by admin
September 23, 2025
Next Post
‘How Do I Know This Place?’

'How Do I Know This Place?'

Olivia Wilde Goes On Outing With Kids Otis & Daisy: Photos – Hollywood Life

Olivia Wilde Goes On Outing With Kids Otis & Daisy: Photos – Hollywood Life

  • Trending
  • Comments
  • Latest
I Only Have More Questions After Another Bizarre Outing With The Harrigans

I Only Have More Questions After Another Bizarre Outing With The Harrigans

April 20, 2025
Amazon Forgot to Take the 2024 MacBook Air Off Sale After Their Big Spring Event

Amazon Forgot to Take the 2024 MacBook Air Off Sale After Their Big Spring Event

April 4, 2025
Ecca Vandal’s “CRUISING TO SELF SOOTHE” video is an ode to skate culture

Ecca Vandal’s “CRUISING TO SELF SOOTHE” video is an ode to skate culture

March 10, 2025
Easy Blueberry Scones (With Frozen Blueberries)

Easy Blueberry Scones (With Frozen Blueberries)

April 10, 2025
A Global Recognition of Indi

A Global Recognition of Indi

April 21, 2025
Tuesday Snapshot – Vivaldi Browser snapshot 3621.3

Tuesday Snapshot – Vivaldi Browser snapshot 3621.3

March 5, 2025
I finally watched The Truman Show

I finally watched The Truman Show

April 6, 2025
Instagram Adds New Teleprompter Tool To Edits

Instagram Adds New Teleprompter Tool To Edits

June 11, 2025
Slide Away Festival Will Reunite Hum, Chapterhouse

Slide Away Festival Will Reunite Hum, Chapterhouse

September 29, 2025
Taylor Swift’s The Life of a Showgirl Trolling Promo Clip

Taylor Swift’s The Life of a Showgirl Trolling Promo Clip

September 29, 2025
Don’t miss your chance to exhibit at Disrupt 2025

Save 15% on TechCrunch Disrupt 2025 Founder Passes (Sept. 29–Oct. 3 Only)

September 29, 2025
What is Parameter-Efficient Fine-Tuning (PEFT) and Why It Matters

What is Parameter-Efficient Fine-Tuning (PEFT) and Why It Matters

September 29, 2025
Beyond The Spider-Verse’s Release Date Is Now Even Sooner

Beyond The Spider-Verse’s Release Date Is Now Even Sooner

September 29, 2025
Tori Spelling Debuts Sleek DIY Bob Cut: ‘I Cut My Own Hair’

Tori Spelling Debuts Sleek DIY Bob Cut: ‘I Cut My Own Hair’

September 29, 2025
Meta Says Link Posts on Threads Are Seeing Better Performance

Threads Invites Creators To Join Its New Communities Element

September 29, 2025
Pros and Cons of Having a Family Lawyer

Pros and Cons of Having a Family Lawyer

September 28, 2025
New Self New Life

Your source for entertainment news, celebrities, celebrity news, and Music, Cinema, Digital Lifestyle and Social Media and More !

Categories

  • Celebrity
  • Cinema
  • Devices
  • Digital Lifestyle
  • Entertainment
  • Music
  • Social Media
  • Softwares
  • Uncategorized

Recent Posts

  • Slide Away Festival Will Reunite Hum, Chapterhouse
  • Taylor Swift’s The Life of a Showgirl Trolling Promo Clip
  • Save 15% on TechCrunch Disrupt 2025 Founder Passes (Sept. 29–Oct. 3 Only)
  • Home
  • Disclaimer
  • DMCA
  • Privacy Policy
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites. slotsfree  creator solana token

No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites.

New Self New Life