0

would someone help me understand this behavior of Java?

I found that running

Object[] objArray = {"A", "B"};  
String[] strArray = (String[]) objArray;

throws a ClassCastException (so far, so good). However,

String[] strArray = {"A", "B"}; 
Object[] objArray = strArray; 
String[] castStrArray = (String[]) objArray;

does not. I have trouble understanding this (I do not see in which ways the 'objArray' in both versions are different). Could someone help me understand the underlying concept?

Best regards!

Bill Hileman
  • 2,730
  • 2
  • 15
  • 23
  • It's too late for you but never too late for others. **Critical information: Arrays are objects theirself.** In the first one, you are first creating an **object array** that has strings inside. You can cast them one by one to strings. However, casting an object array to string array is illegal, it is about the constructor you use because you actually create your object there. The rest is all about referencing to the object. In the second, you are creating a **string array** that has strings inside. Then you cast it to object array and cast it back to string array. Those are legal. – wolfenblut May 27 '22 at 12:59

0 Answers0