Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Character to String, why?

 
Tom Schuman
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://java.sun.com/docs/books/tutorial/java/data/strings.html

On that page they talk about characters and strings. But then there is this example:



Why are they converting the value Character object has to a String? I tried doing it without converting and it works perfectly. Do they have it there just so they could show more methods from the Character class in the example or is there some advantage to do it like that?
[ February 24, 2005: Message edited by: Tom Schuman ]
 
Ray Stojonic
Ranch Hand
Posts: 326
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My guess is that it's done for purposes of clarification.

When providing an Object to a println method, the Object's toString() method will be called, in the example it's done explicitly in the code rather than having Java handle it implicitly.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I tried doing it without converting and it works perfectly

When you do something like:

on the fly the object's toString() method is called. so when you write:

where a is a Character, it is just the same as writing:

There is no advantage to explicitly calling the toString() method, but there is a disadvantage - a might be NULL.
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you do

then the toString() method of someObject is called automagically.... so the result is the same. Some people prefer to call the toString() method themself, some dont... i dont think this will make a difference in the compiled class code.


pascal
 
Tom Schuman
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thx for clarifying this for me
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic