Java - Format Specifier General Formatting

Introduction

The general formatting formats values of any data types.

The following table lists conversions in the general formatting category.

Conversion
Uppercase
Description
'b'


'B'


It produces "true" or "false" based on the value.
It produces "false" for a null argument and for a Boolean false value.
Otherwise, it produces "true."
'h'

'H'

It produces a string that is the hash code value in hexadecimal format.
If the argument is null, it produces "null."
's'



'S'



It produces a string representation of the argument.
If the argument is null, it produces a "null" string.
If the argument implements the Formattable interface, it calls formatTo() method on the argument.
If the argument does not implement the Formattable interface, toString() method is invoked.

The following code uses Boolean, string and hash code formatting conversions.

The hash code formatting conversion ( 'h' and 'H') outputs the hash code value of the argument in a hexadecimal format.

These examples also demonstrate the effect of using the uppercase variants of the conversions.

Demo

public class Main {
  public static void main(String[] args) {
    System.out.printf("'%b', '%5b', '%.3b'%n", true, false, true);
    System.out.printf("'%b', '%5b', '%.3b'%n", "Java", "Javascript", "Json");
    System.out.printf("'%B', '%5B', '%.3B'%n", "Java", "Javascript", "Json");
    System.out.printf("%b %n", 2028);
    System.out.printf("%b %n", new Object());
    // String conversion
    System.out.printf("'%s', '%5s', '%.3s'%n", "Java", "Javascript", "Json");
    System.out.printf("'%S', '%5S', '%.3S'%n", "Java", "Javascript", "Json");
    // Hash Code conversion
    System.out.printf("'%h', '%5h', '%.3h'%n", "Java", "Javascript", "Json");
    System.out.printf("'%H', '%5H', '%.3H'%n", "Java", "Javascript", "Json");
    System.out.printf("%h %n", 2028);
    System.out.printf("%h %n", true);
    System.out.printf("%h %n", new Object());

  }//ww w  .ja va2 s  .  c  o m
}

Result