• 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

Doubt on toString()

 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi friends,

For the following arrays created below, I couldn't able to come to a conlusion why the ouput is like this. Can any one please clear my dilemma on this.

char[] c = new char[0];
System.out.print(c);//The ouput is empty. Why dont it call toString()?
System.out.print(c.toString());//prints hexcode of the array
System.out.print("hi"+c);//for this toString()is getting called

int[] i = new int[0];
System.out.print(i);//The hashCode is printed. Does it calls toString() on this by default?. If yes why it is not called for character arrays?

String str = new String();
System.out.print(str)//The output is empty
System.out.print(str.toString())//The output is still showing as empty.

String[] str1 = new String[0];
System.out.print(str1);//prints the hashcode

Thanks,
Ravindra.
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy ranchers,

Ravindranath asked:

System.out.print(c);//The ouput is empty. Why dont it call toString()?



I guess, the char array is treated as a String. But not like
System.out.print(c.toString() );
because this would call the array's object's toString() and result in a hashcode output.

It is more like
System.out.print(new String(c) );
where the char array is used to build a new String object.


Example

prints:

Note the empty lines.

Why this is so? Perhaps it makes more sense to print out a char array as a String than as just the way objects are printed out (as hashcode when there's no override of toString() ).


Yours,
Bu.
 
reply
    Bookmark Topic Watch Topic
  • New Topic