Why is this type of conversion(array to Object) possible in Java and what does x refer to ?(can I still access the array elements "s1","s2","s3" through x). Where is the array to Object conversion used?
String[] array = {"s1","s2","s3"};
Object x = array;
This is possible because an Array is an Object. When you do this widening conversion, you tell Java "This is an Object and you don't need to know anything else about it." You won't be able to access the array elements anymore , because plain Objects don't support element access. However, you can cast x back to an array, which would let you access its elements again:
String[] array = {"s1","s2","s3"};
Object x = array;
// These will print out the same memory address,
// because they point to the same object in memory
System.out.println(array);
System.out.println(x);
// This doesn't compile, because x is **only** an Object:
//System.out.println(x[0]);
// Cast x to a String[] (or Object[]) to access its elements.
String[] theSameArray = (String[]) x;
System.out.println(theSameArray[0]); // prints s1
System.out.println(((Object[]) x)[0]); // prints s1
This is called a widening reference conversion (JLS Section 5.1.5). x still refers to the array, but Java only knows x as an Object.
You cannot access the array elements directly through x unless you cast it back to String[] first.
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