The code above when executed gives the output as "A". I do not understand why?? Can anybody please explain?? Also, if i modify the code in A and name the method as toString1(), then it gives the output as "A@1971" ..something like that..Why is this so?? Thanx in advance Geeta
System.out is an object of type java.io.PrintStream. The println(Object) method of class PrintStream prints whatever returns from the invocation to String.valueOf(Object). The latter's code is: return (obj == null) ? "null" : obj.toString(); that is, if the object is null, the string literal "null" will be printed, otherwise the toString() method is invoked on the object and the result is returned. In your case, "A" gets printed because toString() is invoked on a1. The java.lang.Object class implements a basic version of the toString method whose code looks as follows: return getClass().getName() + "@" + Integer.toHexString(hashCode()); that is the class name, followed by "@", followed by the hashcode in a hexadecimal string. When you renamed toString() to toString1(), the basic toString() version has been invoked, yielding the result you mentioned.
hi valentin, I had no idea that printstream class prints whatever returns from the invocation to String.valueOf(Object). I checked it and realised that since we r overriding the toString() method of object class, we get the output as "A".I am absolutely clear now. Thanks a lot valentin,
subject: confused with the output from a code (Arrays)