• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Java | toString Method
  1. toString Method

  1. toString Method
    The toString method is defined in the java.lang.Object class and returns the object class name and its internal address:
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    The java.util.Objects class provides utility methods to get the string value code of an object:
    public static String toString(Object o) {
        return String.valueOf(o);
    }
    public static String toString(Object o, String nullDefault) {
        return (o != null) ? o.toString() : nullDefault;
    }
    The java.util.Arrays class provides utility methods to get the string value of an array of objects (including specific overloaded methods for each primitive type). It also provides a utility method to get a deep string value of an array of objects (array of arrays).

    The following is a sample code that show how to implement the toString method.

    • Superclass "P":
      class P {
          Integer id = 1;
      
          @Override
          public String toString() {
              String value = "%s@%X (id:%d)";
              return String.format(Locale.getDefault(), value, getClass().getName(), System.identityHashCode(this), id);
          }
      }
    • Subclass "C":
      class C extends P {
          String code = "default";
      
          @Override
          public String toString() {
              String value = "%s (code:%s)";
              return String.format(Locale.getDefault(), value, super.toString(), code);
          }
      }
© 2025  mtitek