You tin dismiss format String inwards Java either past times using String.format() method or past times using System.printf() method, both uses TextFormat cast to format String input internally. Both of these methods are inspired from C-Style printf() method in addition to formatting teaching are real similar to C e.g. %s for String, %d for numeric, %f for floating betoken value in addition to %n for novel lines etc, but it is non just same every bit C. Some customization convey been made to adapt roughly Java linguistic communication features. Java's String formatting is likewise to a greater extent than strict than C's, for example, if a conversion is incompatible amongst a flag in addition to 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, every bit long every bit yous know nearly them or convey an stance where to refer, yous are good. If your chore involves lots of String formatting materials in addition to so yous volition automatically know the nitty gritty of it e.g. roughly advanced uses of String.format() method, which nosotros volition meet inwards this article.
Many developers likewise confuse betwixt printf() in addition to format(), they are just same, exclusively dissimilar is 1 is declared inwards java.lang.String cast in addition to other is on java.io.PrintStream. Use String.format() method if yous request a formatted String in addition to role System.out.printf() if yous request to display formatted String on the console.
The instant most of import thing yous request 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 teaching yous give.
// formatting String amongst dynamic String in addition to Integer input
System.out.printf("length of String %s is %d %n", "abcd", "abcd".length());
This volition impress "length of String abcd is iv ", yous tin dismiss meet that "abcd" in addition to "4" is dynamically appended into given String based upon formatting teaching in addition to values yous 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", yous tin dismiss meet that fifty-fifty though yous passed Tokyo every bit offset parameter it appeared concluding inwards formatted String because nosotros convey 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", yous tin dismiss meet that today's engagement is nicely formatted inwards MM/dd/yy format. This is belike the easiest way to format a Date every bit String inwards Java, It doesn't require yous to exercise SimpleDateFormat object in addition to handgrip formatting of engagement past times yourself.
// formatting floating betoken release every bit String, yous tin dismiss overstep both float in addition to double
System.out.printf("Value of PIE is %f %n", Math.PI);
This volition impress "Value of PIE is 3.141593 ", yous tin dismiss meet that value of PI is printed upward to v decimal places which are default precision applied past times format() method of String class. Though, yous tin dismiss command upward to how many decimal places yous desire to role every bit shown inwards the adjacent example.
You should likewise banker's complaint that Math.PI is a double constant, which agency yous tin dismiss overstep both float in addition to double variables past times using %f formatting instruction. You tin dismiss meet to a greater extent than examples of formatting float in addition to double inwards my article 5 examples of formatting double in addition to float inwards Java.
// if yous desire to output to endure exclusively upward to for certain decimal house in addition to so yous tin dismiss 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 ", yous tin dismiss meet that value of PI is non exclusively printed upward to 2 decimal places every bit instructed. Btw, yous convey to a greater extent than pick when it comes to formatting numbers inwards Java e.g. yous tin dismiss role NumberFormat in addition to DecimalFormat for to a greater extent than flexibility in addition to to a greater extent than formatting styles.
// next volition format decimals upward to iii decimals
System.out.printf("Value of PIE up-to iii decimals is %.3f", Math.PI);
This instance volition impress "Value of PIE upward to iii decimals is 3.142", yous tin dismiss straightaway meet that value of PI is printed upward to iii decimal places because of formatting teaching "%.3f". You tin dismiss alter it to whatever value yous desire depending upon your requirement.
// adding leading zeros into numbers
int release = 7;
String str = String.format("%03d", 7); // 0007
System.out.printf("original release %d, numeric string amongst padding : %s", 7, str);
You tin dismiss fifty-fifty role the printf() in addition to format() method to add together leading zeros to a number. For example, if yous desire to convert vii to 007, yous tin dismiss but exercise that using format() method every bit shown above. This is peculiarly useful when yous ever convey to post iv digits or v digit code in addition to request to add together leading zeros accordingly. See this tutorial to larn to a greater extent than nearly adding leading zeros to a release inwards Java.
1) Both String.format() in addition to PrintStream.printf() are overloaded to back upward locale-specific formatting.
2) The String.format() method throws java.util.IllegalFormatConversionException if yous overstep 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 in addition to %n is used to insert a novel business inwards formatted String. %n genuinely provide the platform specific business separator every bit returned past times System.getProperty("line.separator"), So its platform independent.
4) The seat of declaration is inwards the club they look inwards source String e.g. if source String is "%s has length %d" in addition to so the offset declaration would endure of String type in addition to the instant declaration would endure of decimal integer type.
5) The String.format() method is strict nearly type, so if formatting flag is %s in addition to so yous must overstep a String object, otherwise it volition throw java.util.IllegalFormatConversionException.
6) You tin dismiss likewise format Date every bit String using String.format() method, surprised? Yes, fifty-fifty I got surprised when I discovered that at that topographic point is a way to format Date inwards Java without using SimpleDateFormat. You tin dismiss role %tD flag to format Date every bit "MM/dd/yy" String.
If yous are novel to Java in addition to desire to larn to a greater extent than nearly its meat features including text, release in addition to currency formatting, the I would propose yous reading a skillful Java mass similar Core Java, Volume 1 tenth Edition past times Cay S. Horstmann. This volition assistance yous to larn essential concepts inwards Java inwards quick fourth dimension inwards to a greater extent than structured ways.
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 mistake but right the formatting teaching or the value yous are passing, both must endure inwards sync to avoid this error.
That's all about how to format String inwards Java. You tin dismiss role String.format() or PrintStream.printf() to format String, which internally uses Formatter class. It allows yous to format dates, floating betoken numbers, numeric etc. Please meet Javadoc of Formatter cast for all kind of formatting instruction. We convey barely touched the surface of dissimilar formatting flags but this is what yous request at 90% of the time. Some of the most mutual uses for formatted String is on toString() method, or formatting float in addition to doubles inwards Java.
Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass
As a programmer, what is most of import to larn regarding String formatting is those flags, every bit long every bit yous know nearly them or convey an stance where to refer, yous are good. If your chore involves lots of String formatting materials in addition to so yous volition automatically know the nitty gritty of it e.g. roughly advanced uses of String.format() method, which nosotros volition meet inwards this article.
Many developers likewise confuse betwixt printf() in addition to format(), they are just same, exclusively dissimilar is 1 is declared inwards java.lang.String cast in addition to other is on java.io.PrintStream. Use String.format() method if yous request a formatted String in addition to role System.out.printf() if yous request to display formatted String on the console.
7 examples of formatting String inwards Java
Here are a brace of examples of formatting String or text inwards Java. There are 2 key things to learn, first, yous tin dismiss role either printf() or format() to format a String. The key departure 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 yous tin dismiss shop or role the way yous want.The instant most of import thing yous request 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 teaching yous give.
// formatting String amongst dynamic String in addition to Integer input
System.out.printf("length of String %s is %d %n", "abcd", "abcd".length());
This volition impress "length of String abcd is iv ", yous tin dismiss meet that "abcd" in addition to "4" is dynamically appended into given String based upon formatting teaching in addition to values yous 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", yous tin dismiss meet that fifty-fifty though yous passed Tokyo every bit offset parameter it appeared concluding inwards formatted String because nosotros convey 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", yous tin dismiss meet that today's engagement is nicely formatted inwards MM/dd/yy format. This is belike the easiest way to format a Date every bit String inwards Java, It doesn't require yous to exercise SimpleDateFormat object in addition to handgrip formatting of engagement past times yourself.
// formatting floating betoken release every bit String, yous tin dismiss overstep both float in addition to double
System.out.printf("Value of PIE is %f %n", Math.PI);
This volition impress "Value of PIE is 3.141593 ", yous tin dismiss meet that value of PI is printed upward to v decimal places which are default precision applied past times format() method of String class. Though, yous tin dismiss command upward to how many decimal places yous desire to role every bit shown inwards the adjacent example.
You should likewise banker's complaint that Math.PI is a double constant, which agency yous tin dismiss overstep both float in addition to double variables past times using %f formatting instruction. You tin dismiss meet to a greater extent than examples of formatting float in addition to double inwards my article 5 examples of formatting double in addition to float inwards Java.
// if yous desire to output to endure exclusively upward to for certain decimal house in addition to so yous tin dismiss 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 ", yous tin dismiss meet that value of PI is non exclusively printed upward to 2 decimal places every bit instructed. Btw, yous convey to a greater extent than pick when it comes to formatting numbers inwards Java e.g. yous tin dismiss role NumberFormat in addition to DecimalFormat for to a greater extent than flexibility in addition to to a greater extent than formatting styles.
// next volition format decimals upward to iii decimals
System.out.printf("Value of PIE up-to iii decimals is %.3f", Math.PI);
This instance volition impress "Value of PIE upward to iii decimals is 3.142", yous tin dismiss straightaway meet that value of PI is printed upward to iii decimal places because of formatting teaching "%.3f". You tin dismiss alter it to whatever value yous desire depending upon your requirement.
// adding leading zeros into numbers
int release = 7;
String str = String.format("%03d", 7); // 0007
System.out.printf("original release %d, numeric string amongst padding : %s", 7, str);
Things to holler back nearly formatting String inwards Java
Now, let's revise in addition to larn few to a greater extent than of import things nearly formatting text or String inwards Java.1) Both String.format() in addition to PrintStream.printf() are overloaded to back upward locale-specific formatting.
2) The String.format() method throws java.util.IllegalFormatConversionException if yous overstep 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 in addition to %n is used to insert a novel business inwards formatted String. %n genuinely provide the platform specific business separator every bit returned past times System.getProperty("line.separator"), So its platform independent.
4) The seat of declaration is inwards the club they look inwards source String e.g. if source String is "%s has length %d" in addition to so the offset declaration would endure of String type in addition to the instant declaration would endure of decimal integer type.
5) The String.format() method is strict nearly type, so if formatting flag is %s in addition to so yous must overstep a String object, otherwise it volition throw java.util.IllegalFormatConversionException.
6) You tin dismiss likewise format Date every bit String using String.format() method, surprised? Yes, fifty-fifty I got surprised when I discovered that at that topographic point is a way to format Date inwards Java without using SimpleDateFormat. You tin dismiss role %tD flag to format Date every bit "MM/dd/yy" String.
If yous are novel to Java in addition to desire to larn to a greater extent than nearly its meat features including text, release in addition to currency formatting, the I would propose yous reading a skillful Java mass similar Core Java, Volume 1 tenth Edition past times Cay S. Horstmann. This volition assistance yous to larn essential concepts inwards Java inwards quick fourth dimension inwards to a greater extent than structured ways.
Errors in addition to Exception spell formatting String
If yous give invalid conversion or formatting flag, hither nosotros had passed %D to format Date but the right flag is %tD, thence 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 mistake but right the formatting teaching or the value yous are passing, both must endure inwards sync to avoid this error.
That's all about how to format String inwards Java. You tin dismiss role String.format() or PrintStream.printf() to format String, which internally uses Formatter class. It allows yous to format dates, floating betoken numbers, numeric etc. Please meet Javadoc of Formatter cast for all kind of formatting instruction. We convey barely touched the surface of dissimilar formatting flags but this is what yous request at 90% of the time. Some of the most mutual uses for formatted String is on toString() method, or formatting float in addition to doubles inwards Java.
Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass
No comments:
Post a Comment