Suppose that I hava a String object reference and I assign it to an Object reference.This would implicitly perform widening.
Object o = "Hello World"
Now we cannot use any String methods on o. My Question is will there be any loss of data because of this typecasting, as in C++ where data would be lost if we cast a float into an int.
If I cast o back to String explicitly will I be able to access the actual String.
There are a lot of methods in Java which has Object type variable as an argument.So I can pass any type of object ref to this argument. Can I convert this object back to the original by narrowing it explicitly?
For objects, you're simply casting the reference. The object (String) still remains intact.
When you pass a String to a method call, you're simply passing the reference to it (as occurs when you encounter a return value). You can check and recast using
if (o instanceof String) {
String s = (String)o;
}
and safely use that string (note that if you're doing this a lot it may point to an incorrect object modelling, but that's another issue)
Note that you also talk about floats/ints, and these are distinct from the above, since they're Java primitives, not references. See here for a discussion on casting primitives. Briefly, you will lose data here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With