class - The connection between 'System.out.println()' and 'toString()' in Java -


what connection between system.out.println() , tostring() in java? e.g:

public class {     string x = "abc";      public string tostring() {         return x;     } }  public class ademo {     public static void main(string[] args) {         obj = new a();         system.out.println(obj);     } } 

if main class runs, gives output "abc". when remove code overrides tostring(), gives output "a@659e0bfd". so, can explain working principle of system.out.println() when use parameter object? connected tostring() method?

system.out printstream. printstream defines several versions of println() function handle numbers, strings, , on. when call printstream.println() arbitrary object parameter, the version of function acts on object. version of function

...calls @ first string.valueof(x) printed object's string value...

looking @ string.valueof(object), see returns

if argument null, string equal "null"; otherwise, value of obj.tostring() returned.

so, long story short, system.out.println(someobject) calls object's tostring() function convert object string representation.

if object defines own tostring() function, called. if don't provide such function, object inherit tostring() 1 of parent classes. in worst case, inherit object.tostring(). version of tostring() defined return

a string consisting of name of class of object instance, at-sign character `@', , unsigned hexadecimal representation of hash code of object.

or, in other words:

getclass().getname() + '@' + integer.tohexstring(hashcode()) 

so, when call system.out.println() on object doesn't define own version of tostring(), might object version looks "classname@somehexnumber".


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -