Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Widening conversion from array to Object (java)

Tags:

java

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;  
like image 385
Natasha Avatar asked Jun 29 '26 22:06

Natasha


2 Answers

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
like image 185
Henry Keiter Avatar answered Jul 02 '26 10:07

Henry Keiter


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.

like image 29
rgettman Avatar answered Jul 02 '26 12:07

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!