The toString() Method of Java

All Java objects have a toString method that determines how the object will look when printed.

The specification of the toString method recommends that all classes define this method. If a class does not define a toString method, it will inherit the toString method of its superclass, which is likely to useless or misleading.

Within the UTC1 class of our example, we can define a suitable toString method like this:

          public String toString () {
              return ((Integer) (100 * h + m)).toString();
          }

Here we see another use for casts. The type of (100 * h + m) is int, which is a primitive (uncapitalized) type, not a reference (capitalized) type. In Java, the values of a primitive type are not considered to be objects. Casting the int expression to Integer also converts the primitive value into a reference value, or object, making it possible to call its toString method.

Some casts of that sort are no longer necessary in the latest versions of Java, but were necessary in earlier versions. Writing an explicit cast, as here, reveals the code that would be executed if the programmer left the cast to be inserted by the Java compiler.