File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Character to String, why?" Watch "Character to String, why?" New topic

Character to String, why?

Tom Schuman

Joined: Dec 30, 2004
Posts: 18

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

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.

Tom Schuman

Joined: Dec 30, 2004
Posts: 18
Thx for clarifying this for me
I agree. Here's the link:
subject: Character to String, why?
It's not a secret anymore!