String Formatting


Advertisements

How to format String in Java is most common problem developer encounter because classic System.out.println() doesn’t support formatting of String while printing on console. For those who doesn’t know What is formatted String ? Here is a simple definition.

A Formatted String is a String which not only display contents but also display it in a format which is widely accepted like including comma while displaying large numbers e.g. 100,000,000 etc. Displaying formatted String is one of need for modern GUI application and thankfully Java has good support for formatting String and all other types like Integers, Double and Date.

1. String.format() & printf() Methods

String.format() and System.out.printf() both works similarly and if you see the signature of both method they also accept variable arguments . Both take minimum two parameters, first of them is formatting instruction and other was actual String or anything which needs to be formatted. Java formatting instructions are both powerful and flexible and allows you to generate formatted String on many different format. Its worth to understand format of "formatting instruction" to take full benefit of String.format() method because this is the only tricky part of String formatting specially if you have not used printf() in past. I have seen developer struggle to understand the formatting behavior because of lack of knowledge of different formatting options available in Java. Check the syntax below to see how we specify formatting instructions in Java :

Syntax:

String.format(Arguments, Objects)

String.format("%[argument number] [flags] [width] [.precision] type", "Object 1", "Object 2", "Object etc.")
  •  %  - is a special character denoting that a formatting instruction follows.
  •  [argument index]  - explicitly denoted the index of the arguments to be formatted. If it not present, arguments will be formatted in the same order as they appear in the arguments list.
  •  [flag]  - i a special formatting instruction. For example, the + flag specifies that a numeric value should always be formatted with a sign, and the 0 flag specifies that 0 is the padding character. Other flags include – that is pad on the right , + pad on the left (if the formatted object is a string). Note that some flags cannot be combined with certain other flags or with certain formatted objects.
  •  [width]  - denotes the minimum number of output characters for that Object.
  •  [.precession]  - denotes the precision of floating point numbers in the output. That is basically the number of decimal digits you wish to print on the output. But it can be used for other types to truncate the output width
  •  type  - along with  % , are the only mandatory formatting arguments. type simply denotes the type of the object that will be formatted in the output.

    •  d  for integers.
    •  s  for strings.
    •  f  for floating point numbers.
    •  x  for integers with Xex format

Basic Example

StringFromatExample.java

package com.javacodegeeks.core.string;

public class StringFromatExample {

	public static void main(String[] args) {

    String number = String.format("Integer : %d\n",15);
    String threeDecimalDigits = String.format("Floating point number with 3 decimal digits: %.3f\n",1.21312939123);
    String eightDecimalDigits = String.format("Floating point number with 8 decimal digits: %.8f\n",1.21312939123);
        
        String combination = String.format("String: %s, integer: %d, float: %.6f", "Hello World",89,9.231435);

		System.out.print(number +  threeDecimalDigits +  eightDecimalDigits +  combination);
	}
}

Result:

Integer : 15
Floating point number with 3 decimal digits: 1.213
Floating point number with 8 decimal digits: 1.21312939
String: Hello World, integer: 89, float: 9.231435

2. Formatting Rules

Here is a basic list of the most important rules when you want to format a String.



Integer formatting

  •  %d  - will print the integer as it is.
  •  %6d  - will print the integer as it is. If the number of digits is less than 6, the output will be padded on the left.
  •  %-6d  - will print the integer as it is. If the number of digits is less than 6, the output will be padded on the right.
  •  %06d  - will print the integer as it is. If the number of digits is less than 6, the output will be padded on the left with zeroes.
  •  %.2d  - will print maximum 2 digits of the integer.

Example

package com.javacodegeeks.core.string;

public class StringFromatExample {

	public static void main(String[] args) {
		
		String columns = String.format("%-12s%-12s%s\n", "Column1", "Column2", "Column3");
		String numbers = String.format("%-12d%-12d%07d\n", 15, 12, 5);
        
        System.out.print(columns + numbers);
	}
}

Result:

Column1     Column2     Column3
15          12          0000005



String formatting

  •  %s  - will print the string as it is.
  •  %15s  - will print the string as it is. If the string has less than 15 characters, the output will be padded on the left.
  •  %-6s  - will print the string as it is. If the string has less than 6 characters, the output will be padded on the right
  •  %08s  - will print maximum 8 characters of the string.

Example

package com.javacodegeeks.core.string;

public class StringFromatExample {

	public static void main(String[] args) {
		
		String headings = String.format("%-12s%-12s%s\n","Column 1","Column 2","Column3");
		String content = String.format("%-12.5s%s", "Hello World","World");
        
        System.out.print(headings + content);
	}

}

Result:

Column 1    Column 2    Column3
Hello       World



Floating Point formatting

  •  %f  - will print the number as it is.
  •  %15f  - will print the number as it is. If the number has less than 15 digits, the output will be padded on the left.
  •  %-15f  - will print the number as it is. If the number has less than 15 digits, the output will be padded on the right.
  •  %.8f  - will print maximum 8 decimal digits of the number.
  •  %9.4f  - will print maximum 4 decimal digits of the number. The output will occupy 9 characters at least. If the number of digits is not enough, it will be padded

Example

package com.javacodegeeks.core.string;

public class StringFromatExample {

	public static void main(String[] args) {
		
		String headings = String.format("%-12s%-12s\n","Column 1","Column 2");		
		String numbers = String.format("%-12.5f%.20f", 12.23429837482,9.10212023134);
        
        System.out.print(headings + numbers);
	}

}

Result:

Column 1    Column 2    
12.23430    9.10212023134000000000

As you can see if you truncate the number of decimal digits, some of the precision is lost. On the other hand if you specify more decimal numbers in the formatting options, the number will be padded is necessary.





java_strings.htm

Advertisements