views:

327

answers:

4

I saw a few topics on SO about this but none really answered my question so here it is:

String s = "a string";
Object o = s;
s = String(o);  // EDIT this line was wrong
s = (String)o;  // EDIT Corrected line

Now this compiles fine but throws a ClassCastException. The only thing is that I thought there was some way to make this work. is there a way to turn an object such as a string in this case back into the object it once was?

EDIT: Sorry everyone, in my haste I wrote it in incorrectly. I was right about how it actually functions i.e. String(o) but the problem was actually due to me trying to return a wrong object in a method. Very sorry about that. Thanks for confirming that that is how you need to cast though!

Thanks

+3  A: 

You want

s = (String)o;

i.e. you cast by putting the object type in parentheses. Note that the object you've created is always a String. The reference however can be a reference to an object, a reference to a String etc.

(I don't believe your example would compile, btw. There isn't an appropriate String constructor)

Brian Agnew
+2  A: 
String s = "a string";
Object o = s;
s = (String)o;

System.out.println(s);
bruno conde
A: 

In addition to the answers from Brian and Bruno: You are not casting in your Code but creating a new String through its constructor.

Janusz
A: 

When you create Object o and assign it to s there is an implicit cast and the string is cast to an object. When this happens you loose some information. So when you try to cast the object back to a string then you are attempting to introduce information that it just doe not have. If you were to have made o a string originally then cast it to an object and then back down again then you wouldn't have had a problem.

uriDium