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.

1
  • Why not freatebitnthe way you wsnt it in the first place? Integer[] ob = new Integer[2];? Commented May 17, 2020 at 0:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.