Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on toString()

 
Ravindranath Chowdary
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • 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.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic