Search code examples
javaarraysreferencetostringprimitive-types

Implementation of toString method in Java


When I want to print an empty array of the Boolean (reference type), the result is as output #1. But when I want to print a primitive boolean type empty array, output #2 is the result. I know that the toString() method in the Object class is running by default. The default implementation of this method is as follows:

this.getClass().getName() + "@" + Integer.toHexString(this.hashCode());

But it is interesting why Z is written in the output of primitive type however for int is I?

public class ToStringApp {
  public static void main(String[] args) {

    Boolean[] refs = new Boolean[1];
    System.out.println(refs);         
    // output #1: [Ljava.lang.Boolean;@3764951d

    boolean[] prims = new boolean[1];
    System.out.println(prims);        
    // output #2: [Z@4b1210ee

    int[] ints = new int[0];
    System.out.println(ints);
    // output #3: [I@4d7e1886

  }
}

Solution

  • That's what the Javadoc of Class's getName() says:

    String java.lang.Class.getName()

    Returns the name of the entity (class, interface, array class,primitive type, or void) represented by this Class object,as a String. ... If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

    Element Type Encoding
    boolean Z
    byte B
    char C
    class or interface Lclassname;
    double D
    float F
    int I
    long J
    short S

    As you can see, B is already taken by byte, so boolean required a different letter.