7 Examples of String.format() in addition to printf() inward Java - Formatting Text in addition to String inward Java

You tin mail away format String inwards Java either past times using String.format() method or past times using System.printf() method, both uses TextFormat course of written report to format String input internally. Both of these methods are inspired from C-Style printf() method together with formatting education are really similar to C e.g. %s for String, %d for numeric, %f for floating betoken value together with %n for novel lines etc, but it is non precisely same equally C. Some customization accept been made to adjust about Java linguistic communication features. Java's String formatting is too to a greater extent than strict than C's, for example, if a conversion is incompatible alongside a flag together with so Java throws an Exception ( java.util.IllegalFormatConversionException), spell inwards C, incompatible flags are silently ignored.


As a programmer, what is most of import to larn regarding String formatting is those flags, equally long equally you lot know almost them or accept an sentiment where to refer, you lot are good. If your undertaking involves lots of String formatting materials together with so you lot volition automatically know the nitty gritty of it e.g. about advanced uses of String.format() method, which nosotros volition run across inwards this article.

Many developers too confuse betwixt printf() together with format(), they are precisely same, alone unlike is i is declared inwards java.lang.String course of written report together with other is on java.io.PrintStream. Use String.format() method if you lot demand a formatted String together with role System.out.printf() if you lot demand to display formatted String on the console.




7 examples of formatting String inwards Java

Here are a couplet of examples of formatting String or text inwards Java. There are ii fundamental things to learn, first, you lot tin mail away role either printf() or format() to format a String. The fundamental divergence betwixt them is that printf() prints the formatted String into console much similar System.out.println() but the format() method provide a formatted String, which you lot tin mail away shop or role the way you lot want.

The instant most of import thing you lot demand to larn for formatting String inwards Java is formatting instructions e.g. %s, %d, %n etc. The whole formatting procedure industrial plant based upon the education you lot give.


// formatting String alongside dynamic String together with Integer input
System.out.printf("length of String %s is %d %n", "abcd", "abcd".length());

This volition impress "length of String abcd is four ", you lot tin mail away run across that "abcd" together with "4" is dynamically appended into given String based upon formatting education together with values you lot passed.


// re-ordering output using explicit declaration indices
System.out.printf("%3$2s, %2$2s, %1$2s %n", "Tokyo", "London", "NewYork" );

This volition impress "NewYork, London, Tokyo", you lot tin mail away run across that fifty-fifty though you lot passed Tokyo equally showtime parameter it appeared concluding inwards formatted String because nosotros accept  re-ordered output using explicity declaration indices.



// formatting Date to String using %D flag, %D is for MM/dd/yy format
System.out.printf("Date inwards MM/dd/yy format is %tD %n", novel Date());

This instance volition impress "Date inwards MM/dd/yy format is 12/07/16", you lot tin mail away run across that today's appointment is nicely formatted inwards MM/dd/yy format. This is in all probability the easiest way to format a Date equally String inwards Java, It doesn't require you lot to exercise SimpleDateFormat object together with handgrip formatting of appointment past times yourself.


// formatting floating betoken seat out equally String, you lot tin mail away travel past times both float together with double
System.out.printf("Value of PIE is %f %n", Math.PI);

This volition impress "Value of PIE is 3.141593 ", you lot tin mail away run across that value of PI is printed upward to v decimal places which are default precision applied past times format() method of String class. Though, you lot tin mail away command upward to how many decimal places you lot desire to role equally shown inwards the side past times side example.

You should too Federal Reserve annotation that Math.PI is a double constant, which agency you lot tin mail away travel past times both float together with double variables past times using %f formatting instruction. You tin mail away run across to a greater extent than examples of formatting float together with double inwards my article  5 examples of formatting double together with float inwards Java.


// if you lot desire to output to endure alone upward to sure as shooting decimal house together with so you lot tin mail away specify
// inwards your formatting instruction, next volition format String upward to 2 decimals
System.out.printf("Value of PIE upward to 2 decimal house is %.2f %n", Math.PI);

This code volition impress "Value of PIE upward to 2 decimal house is 3.14 ", you lot tin mail away run across that value of PI is non alone printed upward to ii decimal places equally instructed.  Btw, you lot accept to a greater extent than selection when it comes to formatting numbers inwards Java e.g. you lot tin mail away role NumberFormat together with DecimalFormat for to a greater extent than flexibility together with to a greater extent than formatting styles.


// next volition format decimals upward to three decimals
System.out.printf("Value of PIE up-to three decimals is %.3f", Math.PI);

This instance volition impress "Value of PIE upward to three decimals is 3.142", you lot tin mail away straight off run across that value of PI is printed upward to three decimal places because of formatting education "%.3f". You tin mail away alter it to whatever value you lot desire depending upon your requirement.


// adding leading zeros into numbers
int seat out = 7;      
String str = String.format("%03d", 7);  // 0007    
System.out.printf("original seat out %d, numeric string alongside padding : %s", 7, str);

You tin mail away fifty-fifty role the printf() together with format() method to add together leading zeros to a number. For example, if you lot desire to convert vii to 007, you lot tin mail away simply exercise that using format() method equally shown above. This is peculiarly useful when you lot ever accept to mail four digits or v digit code together with demand to add together leading zeros accordingly.  See this tutorial to larn to a greater extent than almost adding leading zeros to a seat out inwards Java.

 You tin mail away format String inwards Java either past times using  vii Examples of String.format() together with printf() inwards Java - Formatting Text together with String inwards Java



Things to shout out upward almost formatting String inwards Java

Now, let's revise together with larn few to a greater extent than of import things almost formatting text or String inwards Java.

1) Both String.format() together with PrintStream.printf() are overloaded to back upward locale-specific formatting.

2) The String.format() method throws java.util.IllegalFormatConversionException if you lot travel past times in-compatible type e.g. passing Integer for flag %s, which expects a String object.

3) Some of the most mutual flags are %s for String, %d for decimal integer together with %n is used to insert a novel describe of piece of job inwards formatted String. %n genuinely provide the platform specific describe of piece of job separator equally returned past times System.getProperty("line.separator"), So its platform independent.

4) The seat of declaration is inwards the gild they seem inwards source String e.g. if source String is "%s has length %d" together with so the showtime declaration would endure of String type together with the instant declaration would endure of decimal integer type.

5) The String.format() method is strict almost type, so if formatting flag is %s together with so you lot must travel past times a String object, otherwise it volition throw java.util.IllegalFormatConversionException.

6) You tin mail away too format Date equally String using String.format() method, surprised? Yes, fifty-fifty I got surprised when I discovered that in that location is a way to format Date inwards Java without using SimpleDateFormat. You tin mail away role %tD flag to format Date equally "MM/dd/yy" String.


If you lot are novel to Java together with desire to larn to a greater extent than almost its inwardness features including text, seat out together with currency formatting, the I would propose you lot reading a skilful Java majority similar Core Java, Volume 1 tenth Edition past times Cay S. Horstmann. This volition assistance you lot to larn essential concepts inwards Java inwards quick fourth dimension inwards to a greater extent than structured ways.



Errors together with Exception spell formatting String

If you lot give invalid conversion or formatting flag, hither nosotros had passed %D to format Date but the right flag is %tD, thus this error.

Exception inwards thread "main" java.util.UnknownFormatConversionException: Conversion = 'D'
at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2646)
at java.util.Formatter$FormatSpecifier.(Formatter.java:2675)
at java.util.Formatter.parse(Formatter.java:2528)
at java.util.Formatter.format(Formatter.java:2469)
at java.util.Formatter.format(Formatter.java:2423)
at java.lang.String.format(String.java:2790)

To solve this fault simply right the formatting education or the value you lot are passing, both must endure inwards sync to avoid this error.


That's all about how to format String inwards Java. You tin mail away role String.format() or PrintStream.printf() to format String, which internally uses Formatter class. It allows you lot to format dates, floating betoken numbers, numeric etc. Please run across Javadoc of Formatter course of written report for all form of formatting instruction. We accept barely touched the surface of unlike formatting flags but this is what you lot demand at 90% of the time. Some of the most mutual uses for formatted String is on toString() method, or formatting float together with doubles inwards Java.

Subscribe to receive free email updates:

0 Response to "7 Examples of String.format() in addition to printf() inward Java - Formatting Text in addition to String inward Java"

Posting Komentar