This week's book giveaways are in the iOS and Features new in Java 8 forums. We're giving away four copies each of Barcodes with iOS: Bringing together the digital and physical worlds and Core Java for the Impatient and have the authors on-line! See this thread and this one for details.
Hi, In java new Date() prints the current date with time. but when i try to print any of class object it prints the memory location i.e(new Test() prints test@2e3ee...). So why is so, because both are objects why only date object prints date not the memory location.....
Because the Date() class overrides Object.toString(). If a class doesn't override this method, the implementation defined on Object is called, which just prints an object's class name and memory location. [ March 16, 2008: Message edited by: Dan Murphy ]
When you print an object, println() calls String.valueOf(theObject), which calls theObject.toString() if "theObject" is not null. Therefore, if a class overrides the toString() method to return something interesting, that's what you see when you print the object. The "memory address" (actually not, but that's another story) is what java.lang.Object.toString() returns, so it's what you get by default for a class that doesn't override this method.
Hi, thanks for your reply... one more question in java.. what is the difference between tostring() method which is present in object class and toString() method in String class... i.e(Object.tostring() and String.toString()).. why java has two tostring() methods implemented in java.. why cant any one be used???
toString is used to display information on an object. Now for Object there is no data to show, so Sun has decided the method should show the class name and the hexidecimal hash code. For String however, there is something to show - the contents of the String. Therefore, toString returns the String itself. Similarly, for most Collection classes, toString returns a String starting with [ followed by all elements separated by a , and ending with a ].
If you create a new class, it inherits toString from its super class. If you have extra data to show you can choose to override toString to display the data you feel is more appropriate. For a Person class, that could be the name.