Java String Format Examples

This article shows you how to format a string in Java, via String.format().

Here is the summary.

Conversion Category Description
%b, %B general true of false
%h, %H general hash code value of the object
%s, %S general string
%c, %C character unicode character
%d integral decimal integer
%o integral octal integer, base 8
%x, %X integral hexadecimal integer, base 16
%e, %E floating point decimal number in scientific notation, 1.000000e+02
%f floating point decimal number
%g,%G floating point decimal number, rounding for the precision
%a,%A floating point hexadecimal floating-point, 0x1.4333333333333p3
%t,%T date/time prefix for date and time conversion
%% percent display literal ‘%’
%n line separator new line, System.getProperty("line.separator")

Further Reading- Formatter JavaDoc.

1. Simple

JavaStringFormat1.java

package com.mkyong;

public class JavaStringFormat1 {

    public static void main(String[] args) {

        String result = String.format("%s is %d", "mkyong", 38);     // mkyong is 38
        System.out.println(result);

        String result2 = String.format("%d + %d = %d", 1, 1, 1 + 1); // 1 + 1 = 2
        System.out.println(result2);

        String result3 = String.format("%s = %f", "PI", Math.PI);    // PI = 3.141593
        String result4 = String.format("%s = %.3f", "PI", Math.PI);  // PI = 3.142
        System.out.println(result3);
        System.out.println(result4);

    }

}

Output


mkyong is 38
1 + 1 = 2
PI = 3.141593
PI = 3.142

2. Argument

We can reorder the arguments with %{index}${conversion}.

  • %1$ – first argument
  • %2$ – second argument
  • %3$ – third argument
  • %{index}$ – {index} argument
JavaStringFormat2.java

package com.mkyong;

public class JavaStringFormat2 {

    public static void main(String[] args) {

        String a1 = "hello1";
        String a2 = "hello2";
        Integer a3 = 333;

        String result = String.format("Test: %3$d, %1$s, %1$s, %2$s", a1, a2, a3);

        System.out.println(result);
    }

}

Output


Test: 333, hello1, hello1, hello2

3. String

JavaStringFormat3.java

package com.mkyong;

public class JavaStringFormat3 {

    public static void main(String[] args) {

        String input = "Hello World";

        // default
        String result1 = String.format("|%s|", input);              // |Hello World|

        // this %s has length of 20, format as %20s, pad 20 characters
        // default right-justified
        String result2 = String.format("|%20s|", "Hello World");    // |         Hello World|

        // left-justified
        String result3 = String.format("|%-20s|", "Hello World");   // |Hello World         |

        // max length = 5
        String result4 = String.format("|%.5s|", "Hello World");    // |Hello|

        // left pad with $
        String result5 = String.format("|%20s|", "Hello World")     // |$$$$$$$$$Hello$World|
                .replace(' ', '$');

        // left pad with $, ignore spaces in string
        String result6 = padLeft("Hello World", 20, "$");          // $$$$$$$$$Hello World

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
        System.out.println(result5);
        System.out.println(result6);

    }

    public static String padLeft(String str, int width, String padWith) {

        String result = "";
        String temp = String.format("%" + width + "s", str);
        if (temp.length() > str.length()) {
            result = temp.substring(0, temp.length() - str.length()).replace(" ", padWith);
        }
        result += str;
        return result;

    }


}

Output


|Hello World|
|         Hello World|
|Hello World         |
|Hello|
|$$$$$$$$$Hello$World|
$$$$$$$$$Hello World

4. Integer

JavaStringFormat4.java

package com.mkyong;

public class JavaStringFormat4 {

    public static void main(String[] args) {

        // default
        String result1 = String.format("|%d|", 100);                // |100|

        // this %d has length of 20, format as %20d, pad 20 characters
        // default right-justified
        String result2 = String.format("|%20d|", 100);              // |                 100|

        // left-justified
        String result3 = String.format("|%-20d|", 100);             // |100                 |

        // left pad with 0
        String result4 = String.format("|%020d|", 100);             // |00000000000000000100|

        // prefix with +
        String result5 = String.format("|%+20d|", 100);             // |                +100|

        // negative
        String result6 = String.format("|%20d|", -100);             // |                -100|

        // octal
        String result7 = String.format("|%20o|", 100);              // |                 144|

        // hex
        String result8 = String.format("|%20x|", 30);               // |                  1e|

        // prefix 0x with #
        String result9 = String.format("|%#20x|", 30);              // |                0x1e|

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
        System.out.println(result5);
        System.out.println(result6);
        System.out.println(result7);
        System.out.println(result8);
        System.out.println(result9);

    }

}

Output


|100|
|                 100|
|100                 |
|00000000000000000100|
|                +100|
|                -100|
|                 144|
|                  1e|
|                0x1e|

5. Floating Points

JavaStringFormat5.java

package com.mkyong;

public class JavaStringFormat5 {

    public static void main(String[] args) {

        double pi = Math.PI;

        // default
        String result1 = String.format("%f", pi);       // 3.141593

        // 2 decimal points
        String result2 = String.format("%.2f", pi);     // 3.14

        String result3 = String.format("%e", pi);       // 3.141593e+00

        String result4 = String.format("%a", pi);       // 0x1.921fb54442d18p1

        // right
        String result5 = String.format("|%20f|", pi);   // |            3.141593|

        // left
        String result6 = String.format("|%-20f|", pi);  // |3.141593            |

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
        System.out.println(result5);
        System.out.println(result6);

    }

}

Output


3.141593
3.14
3.141593e+00
0x1.921fb54442d18p1
|            3.141593|
|3.141593            |

6. FAQs

6.1 Convert Decimal to Binary, 4 bytes, and pad left with 0.


  // 1100100
  String result1 = String.format("%s", Integer.toBinaryString(100));

  // 00000000000000000000000001100100
  String result2 = String.format("%32s", Integer.toBinaryString(100)).replace(" ", "0");

  // 00000000000000011110001001000000
  String result3 = String.format("%32s", Integer.toBinaryString(123456)).replace(" ", "0");

Please suggest some of your favor String.format examples in the below comments.

References

Image

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Nagasai R
5 years ago

I have an requirement where a string can have any length. but i have to fix to 38 finally.
if length is > 38, substring from 1 to 38 bytes. if length is < 38 pad spaces at last