Programming & Scripting Tutorials

Java: Formatting Strings



Often you will want to display some values in a certain way on the screen, if you want to output certain things a lot, or do things with them, then you might want to convert the whole phrase into a string.

We can do this via the "String.format" method.
This is a simple example of using it:

        int d = 27;
        int m = 11;
        int y = 2009;
        String Two = (String.format("%d/%d/%d", d, m, y));
        System.out.println(Two);

However as you may have found out from experimenting, "%d" only holds integers.
To get other datatypes in the string we can use similar but different methods. This is an example with strings:

        String string = "gourmand";
        String meaning = "A lover of good food.";
        String Two = (String.format("The word of the day is: %s.\nThis means: %s", string, meaning));
        System.out.println(Two);

You can also achieve the above like this:

String Two = (String.format("The word of the day is: %s.\nThis means: %s", "gourmand", "A lover of good food."));
        System.out.println(Two);

This is short list of some of the ways to display different datatypes in the string:

"%c" - character
"%d" - (decimal) integer number
"%e" - exponential floating-point number
"%f" - floating-point number
"%i" - integer
"%o" - octal number
"%s" - a string of characters
"%u" - unsigned decimal (integer) number
"%x" - number in hexadecimal
"%%" -print a percent sign

This Java tutorial was written by


Back to Java

Advertisement: