class test
{
public static void main(String args[])
{
test ob=new test();
String st=new String("it is a string");
System.out.println(ob);
System.out.println(st);
}
}
in this code,ob is a reference of test class and st is a reference of string class.
while printing ob it shows the reference but st prints the value i.e.”it is a string”.. why?
Because you haven’t overridden
toString()in yourtestclass so it uses the one fromObject(the parent class of all objects in java) which is simply going to output the class name and hashcode.Josh Bloch outlines this in “Effective Java”:
http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf
(See: “Item 9: Always override toString”)