This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Character to String, why? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Character to String, why?" Watch "Character to String, why?" New topic
Author

Character to String, why?

Tom Schuman
Greenhorn

Joined: Dec 30, 2004
Posts: 18
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

Joined: Aug 08, 2003
Posts: 326
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

Joined: Apr 14, 2004
Posts: 10336


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.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547
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

Joined: Dec 30, 2004
Posts: 18
Thx for clarifying this for me
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Character to String, why?
 
Similar Threads
adding all the numbers in a string
stringbuffer?
Difference
parsing string to Integer
regarding regex syntax