Java

Object toString in Java

In Java, an object is the instance of a class, or it is an array. There is a class called, Object. This Object should not be confused with an object, which is the instance of a class. “Object”, beginning with uppercase ‘O’, is the name of a class, a special class. In Java, the uppermost ancestor of all classes is this class, Object. The object can be instantiated into a class, object (optionally named, with lowercase, ‘o’). However, it is not necessary to instantiate the special class, Object. All classes, which are predefined or programmer-defined classes, are inherited from this class, Object.

The Object class has a method called, toString(). This method returns a string representation of the object of a normal class. All classes inherit this method from Class Object. Each array (as an object) has a similar method.

Unfortunately, this string representation of the object is a short text code (short string literal text). It is not very useful, though it can be decoded. Such decoding is not addressed in this article. And so, the programmer has to override this method in order to have a representation of the object; the computer user will appreciate that. The overriding is addressed in this article.

Default Behavior of toString() Method

Primitive Types

Primitive types such as the int exist in their own right. However, each primitive type in Java has a corresponding class (wrapper). When it comes to converting primitive objects to strings, it is the corresponding classes that should be used. The following program illustrates this for the int. The corresponding class for int is the Integer class.

    public class TheClass {
        public static void main(String[] args) {
            Integer in = 5;
            String str = in.toString();
System.out.println(str);
        }
    }

The output is 5. If “Integer” was typed as int, then an error message would have been issued at compile time. The toString() method of the greatest ancestor class has been employed here, without any issue. That is, the integer, 5 has been converted to a string and printed without any issue. However, if the class was a programmer-defined class or another type of predefined class, then there would have been some issue.

Programmer Defined Class

Consider the following program that prints out the representation of the programmer defined object, obj:

    class AClass {
        int prop1 = 1;
        int prop2 = 2;
        void mthd () {
System.out.println("seen");
        }
    }

    public class TheClass {
        public static void main(String[] args) {
AClass obj = new AClass();
            String str = obj.toString();
System.out.println(str);
        }
    }

The output is:

This is a short coded text – not very useful to the user. The user might have preferred something like:

prop1 => 1;

prop2 => 2;

These are the different properties (fields) and their values. What separates a property from its value in the printout is “ => ”, which should be introduced by the programmer. In a question like this, the methods are not usually printed.

Array

Consider the following program, where the array as an object, arr, should be printed:

    public class TheClass {
        public static void main(String[] args) {
String[] arr = new String[] {"one", "two", "three"};
            String str = arr.toString();
System.out.println(str);
        }
    }

The output is,

[Ljava.lang.String;@d716361

which is another text code. Is that what you wanted? You would have loved to see something like:

one, two, three

where the element separator is “, ”.

List

Consider the following program, where an ArrayList as an object, al, should be printed:

    import java.util.*;
    public class TheClass {
        public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("one"); al.add("two"); al.add("three");
            String str = al.toString();
System.out.println(str);
        }
    }

The output is:

[one, two, three]

The output is quite good! This means that the programmer does not have to override the Object.toString() method when it concerns the ArrayList (or possible list in general). However, when it comes to programmer-defined objects or the array, the programmer needs to override the method.

Map

Consider the following program, where a HashMap as an object, hm, should be printed:

    import java.util.*;
    public class TheClass {
        public static void main(String[] args) {
            HashMap hm = new HashMap();
hm.put("one", 1); hm.put("two", 2); hm.put("three", 3);
            String str = hm.toString();
System.out.println(str);
        }
    }

The output is:

{one=1, two=2, three=3}

The output is quite good! The key/value pairs are distinguishable, with the element separator, being, “, ”. This means that the programmer does not have to override the Object.toString() method, when it concerns the HashMap (or possible map in general). However, when it comes to programmer-defined objects or the array, the programmer needs to override the method.

The rest of this article deals with the overriding of the Object.toString() inherited method of the programmer-defined object and the array.

Overriding toString()

Array

With the array, today, the overriding is indirect or workaround. Java has a class called, Arrays. This class has the toString Method, already overridden by Java. In the class, the toString() method is static: this means that the Arrays class does not have to be instantiated for its toString() method to be used. Here, the toString() method takes an argument, which is the identifier of the array. It produces an output, where the separator is “, ”. Class Arrays, is in the java.util.* package. The following program shows the workaround for arrays:

    import java.util.*;
    public class TheClass {
        public static void main(String[] args) {
double[] arr = new double[] {10.1, 20.2, 30.3};
            String str = Arrays.toString(arr);
System.out.println(str);
        }
    }

The output is:

[10.1, 20.2, 30.3]

The output is quite good! And so, today, the programmer no longer needs to code an overriding method, for the toString() method, for Java array. The programmer does a workaround with Arrays and its toString().

Programmer Defined Object

With programmer defined class, the toString() method of the Object class, just has to be redefined, as illustrated in the following programmer defined class:

    class AClass {
        int prop1 = 1;
        int prop2 = 2;
        void mthd () {
System.out.println("seen");
        }
        @Override
        public String toString() {
            String str1 = "prop1 => " + this.prop1;
            String str2 = "prop2 => " + this.prop2;
            return str1 + '\n' + str2;
        }
    }

The technique is to use the string concatenation operator, + to be joining non-string literals with string literals. The preceding “@Override” prevents certain errors in the overridden method. Redefinition here is overriding. A programmer-defined class corresponds to the programmer-defined object. The following Java main() method is appropriate for the above class:

    public class TheClass {
        public static void main(String[] args) {
AClass obj = new AClass();
            String str = obj.toString();
System.out.println(str);
        }
    }

The output is:

prop1 => 1

prop2 => 2

This output is better appreciated by the user than the short text code, “[email protected]”. Do not forget that the overriding definition takes place in the class of interest.

Conclusion

The Object class has a method called, toString(). This method returns a string representation of the object of a class. All classes inherit this method from Class Object. Each array (as an object) has a similar method. Each class needs overriding of this method, indirectly or directly.

With primitive types, use the reference types (e.g., Integer for int), where Java already has a predefined overridden toString() method, which is satisfactory. With lists and maps, too, Java already has a predefined overridden toString() method, which is satisfactory. With an array, do a workaround: use the toString() method of the Arrays class. With the programmer-defined class, do the actual overriding, using the string concatenation operator, +, as often as possible.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.