• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

confused with the output from a code (Arrays)

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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[0].
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.
 
Geeta Gune
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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,
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic