Introduction
In this tutorial, we will learn how to skip or display % in a String using String.format
MyStringFormatter .java
public class MyStringFormatter {
public static void main(String[] args) {
System.out.println(String.format( "Your score is %d % " ,65) );
}
}
Output
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = ' ' at java.base/java.util.Formatter.checkText(Formatter.java:2732) at java.base/java.util.Formatter.parse(Formatter.java:2718) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.util.Formatter.format(Formatter.java:2609) at java.base/java.lang.String.format(String.java:2897) at MyStringFormatter.main(MyStringFormatter.java:4)
Solution
To display a % in String when using String.format, you have to escape a % with % i.e. %%
public class MyStringFormatter {
public static void main(String[] args) {
System.out.println(String.format( "Your score is %d %% " ,65) );
}
}
Output
Your score is 65 %
This is a useful Java tutorial that clearly explains a common formatting mistake when using String.format(). The example demonstrates why a single percent sign can cause an UnknownFormatConversionException and how escaping it with %% correctly displays the percentage symbol in the output. Such small details are important when formatting scores, percentages, and other numerical values in Java applications.
ReplyDeleteDevelopers who want to strengthen their Java programming skills and learn to build complete applications can explore the Java Full Stack Developer Course. Understanding Java fundamentals, string manipulation, exception handling, and application development provides a strong foundation for working on real-world projects.
For developers interested in building RESTful backend services and integrating them with modern frontend frameworks, the JAX-RS Angular Course is also relevant. Learning how Java REST APIs work with Angular can help developers understand the different components involved in full-stack application development.
ReplyDelete