0

At first, excuse me if this question seems stupid. Actually, I am new to Java programing. I have the following code:

public class Test{
    public static void main(String[] args){
        Object[] ob = new Object[2];
        ob[0] = new Integer("1");
        ob[1] = new Integer("2");

        Integer[] o = (Integer)ob;
        System.out.println(o.length());
    }

}

when compiling this code a classCastException exception is thrown. Why?. I know that Object type can not be cast to Integer type. But, in fact, each element of the array ob is an instance of Integer class which means the casting is logically true. Am I mistaken?.

Thanks in advance.

Hussein Eid
  • 209
  • 2
  • 9

1 Answers1

0

No, it is not ok.

Consider if this would be valid:

Object[] ob = new Object[2];
ob[0] = new Integer("1");
ob[1] = new Integer("2");

Integer[] o = (Integer)ob;
ob[0] = "Hello :)";

What do you expect o[0] to return?
An Integer?
Or the String "Hello"?

This would work if you created the array with new Integer[2] - then you would get a ClassCastException when you try to put the String into it.

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73