Escape percent sign in String’s format method in java

Escape percent sign in java

In this post, we will see how to escape Percent sign in String’s format() method in java.

Escape Percent Sign in String’s Format Method in Java

String’s format() method uses percent sign(%) as prefix of format specifier.
For example:
To use number in String’s format() method, we use %d, but what if you actually want to use percent sign in the String.

If you want to escape percent sign in String’s format method, you can use % twice (%%).

Let’s see with the help of example:

package org.arpit.java2blog;

public class EscapePercentSignStringFormat {

    public static void main(String[] args) {
        String percentSignStr = String.format("10 out of 100 is %d%%", 10);
        System.out.println(percentSignStr);
    }
}

Output:

10 out of 100 is 10%

As you can see, we have used %% to escape percent symbol in 10%.

Escape Percent Sign in printf() Method in Java

You can apply same logic in printf method to print percent sign using System.out.printf() method.

package org.arpit.java2blog;

public class EscapePercentSignStringFormat {

    public static void main(String[] args) {
        System.out.printf("10 out of 100 is %d%%", 10);
    }
}

Output:

10 out of 100 is 10%

That’s all about How to escape percent sign in String’s format method in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.