Unable to assign primitives to Object array in Eclipse

Viewed 1171

I am initiating object array as below:

Object a[] = new Object[4];

a[0] = 1; //while assigning integer value, am getting an error: "Type mismatch: Cannot convert Integer to Object
a[1] = 'A'; //while assigning char value, am getting an error: "Type mismatch: Cannot convert char to Object
a[2] = 12.33//while assigning integer value, am getting an error: "Type mismatch: Cannot convert double to Object
a[3] = "Hello"; //Accepting only string values.

PLease suggest where went wrong? is it configuration issue? I am using:

Java Version jdk1.8.0_151,
jre1.8.0_151,

Eclipse Java EE IDE for Web Developers.
Version: Oxygen.2 Release (4.7.2)
Build id: 20171218-0600
3 Answers

This is exactly the error message you would be getting if you are using a compiler compliance level lower than 5. Note that this is different from the Java version on your system. See the fix here https://stackoverflow.com/a/24591529/11595728 .

int, float, double, and char are all primitive types so they cannot be "converted" as Object.

Strings are Objects, therefore, the can be added in the array.

To achieve what you probably want, you can convert them to their equivalent Object:

Object a[] = new Object[4];
a[0] = Integer.valueOf(1); 
a[1] = Character.valueOf('A');
a[2] = Float.valueOf(12.33);
a[3] = "Hello";

I have not encountered the problem you described. I think it is automatically boxed, At least in my configuration environment.

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Object a[] = new Object[4];

        a[0] = 1; //while assigning integer value, am getting an error: "Type mismatch: Cannot convert Integer to Object
        a[1] = 'A'; //while assigning char value, am getting an error: "Type mismatch: Cannot convert char to Object
        a[2] = 12.33;//while assigning integer value, am getting an error: "Type mismatch: Cannot convert double to Object
        a[3] = "Hello"; //Accepting only string values.
        for(Object i:a) {
            System.out.println(i.toString());
        }
    }

right click -> Run As -> Java Application, the console output:

1
A
12.33
Hello
Related