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

Here is the summary.

ConversionCategoryDescription
%b, %Bgeneraltrue of false
%h, %Hgeneralhash code value of the object
%s, %Sgeneralstring
%c, %Ccharacterunicode character
%dintegraldecimal integer
%ointegraloctal integer, base 8
%x, %Xintegralhexadecimal integer, base 16
%e, %Efloating pointdecimal number in scientific notation, 1.000000e+02
%ffloating pointdecimal number
%g,%Gfloating pointdecimal number, rounding for the precision
%a,%Afloating pointhexadecimal floating-point, 0x1.4333333333333p3
%t,%Tdate/timeprefix for date and time conversion
%%percentdisplay literal ‘%’
%nline separatornew line, System.getProperty("line.separator")

Further Reading- Formatter JavaDoc.

1. Simple

JavaStringFormat1.java

package com.favtuts.string.format;

public class JavaStringFormat1 {

    public static void main(String[] args) {
        
        String result = String.format("%s is %d", "favtuts", 38);   //favtuts 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

favtuts 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.favtuts.string.format;

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.favtuts.string.format;

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 lengh 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()) {
            // cut the left part for padding
            result = temp.substring(0, temp.length() - str.length()).replace(" ", padWith);
        }
        str = temp;
        result += str;
        return result;
    }

}

Output

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

4. Integer

JavaStringFormat4.java

package com.favtuts.string.format;

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);

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

5. Floating Points

JavaStringFormat5.java

package com.favtuts.string.format;

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.

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-string

References

Leave a Reply

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