• Home
  • LLMs
  • Docker
  • Kubernetes
  • Java
  • All
  • About
Java | toString() Method
  1. toString() Method
  2. Example

  1. toString() Method
    The toString() method is defined in the java.lang.Object class and returns a string representation consisting of the object's class name followed by the "@" symbol and its hash code in hexadecimal format:
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    The java.util.Objects class provides utility methods for safe string conversion of objects:
    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 string representations of arrays, including specific overloaded methods for each primitive type and deepToString() for nested arrays.
  2. Example
    The following example demonstrates how to properly implement the toString() method with inheritance:

    • Superclass "P":
      import java.util.Locale;
      
      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