0

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

1
  • That last row compiles for you? Commented Aug 6, 2009 at 14:01

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

Comments

2
String s = "a string";
Object o = s;
s = (String)o;

System.out.println(s);

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.