Space format specifiers in Java

Java 8Object Oriented ProgrammingProgramming

For format specifier, import the following package −

import java.util.Formatter;

Create a formatter object and set space format specifier −

Formatter f = new Formatter();
f.format("% d", -50);
System.out.println(f);
f = new Formatter();
f.format("% d", 90);
System.out.println(f);
f = new Formatter();
f.format("%10d", -50);
System.out.println(f);
f = new Formatter();
f.format("% 10d", 90);
System.out.println(f);

The following is an example displaying different forms of space format specifiers −

Example

 Live Demo

import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      f.format("% d", -50);
      System.out.println(f);
      f = new Formatter();
      f.format("% d", 90);
      System.out.println(f);
      f = new Formatter();
      f.format("%10d", -50);
      System.out.println(f);
      f = new Formatter();
      f.format("% 10d", 90);
      System.out.println(f);
      f = new Formatter();
      f.format("%12.2f", -7.598);
      System.out.println(f);
      f = new Formatter();
      f.format("% 12.3f", 90.87787);
      System.out.println(f); 
   }
}

Output

-50
90
   -50
   90 
   -7.60
   90.878
raja
Published on 21-Dec-2018 16:23:46
Advertisements