is the following code snippet:

           String[] str = {"Abc","Ghi","Def","Mno"};
           Object[] obj = str;
           String[] p = (String[]) obj;

same as :

          String[] str = {"Abc","Ghi","Def","Mno"};
          Object[] obj = str;
          String str1 = (String) obj[0];
          String str2 = (String) obj[1];
          String str3 = (String) obj[2];
          String str4 = (String) obj[3];

How is typecasting an array as in first code different from typecasting individual elements?Is it the same?

0

For a start, in the first case you end up with a variable of type String[], but in the second case you end up with four variables of type String.
What’s the difference between an array and a bunch of variables? 🙂

Assuming you’re more interested in the difference between the equivalent code producing an array:

Object[] obj = str;
String[] p = (String[]) obj;

and

Object[] obj = str;
String[] p = new String[] {
    (String)obj[0],
    (String)obj[1],
    (String)obj[2],
    (String)obj[3]};

the main differences are:

  • The second code snippet creates a new array. If you were to do str[2] = "blah"; after executing the first snippet, then p[2] would also contain “blah”, because p and str are references to the same array. With the second snippet, p[2] would still contain "Ghi".
  • The second code snippet works regardless of the type of str. If str was actually created as:

    Object[] str = {"Abc","Ghi","Def","Mno"};
    

    then the first snippet would throw a ClassCastException because the object obj refers to is not a String[]. The second snippet would work fine provided all the elements are Strings.

  • The second snippet throws an ArrayIndexOutOfBoundsException if the array has less than four elements, and only copies the first four elements if it has more than four. However, you could easily write a version that would work for an arbitrary number of elements.

The difference is where the types are checked:

       String[] p = (String[]) obj;

Here we check if obj really is a String[]. Having checked that, we know that every element in obj is a String.

      String str1 = (String) obj[0];
      String str2 = (String) obj[1];
      String str3 = (String) obj[2];
      String str4 = (String) obj[3];

Here, we check each element individually. We never check if obj is really a String[], and indeed this code will work if it isn’t. Instead, we check each element individually to see if it is a String.