public class Test { public static void main(String[] args) { Object[] objectArray = new Object[3]; objectArray[0] = "Hello World"; objectArray[1] = new Integer(10); objectArray[2] = new Character('a'); System.out.println(objectArray[0]); System.out.println(objectArray[1]); System.out.println(objectArray[2]); } }
The output is expected to be:
Hello World 10 aThe ideal use case of using Array of Object in Java is when we can't narrow down the family of class that will be involved as values. Where tracing the root class has no commonality other than the Object class.
Object[] thisIsAnObjectArray;
The other way is by placing the square brackets after the variable name in the declaration.
Object thisIsAnObjectArray[];
Both statements will have the same result - declaring an array of Object that is initially null.
Array of Objects Declaration With SizeWe can also declare an array of objects with an initial size, let's say 4.
Object[] objectArray = new Object[4]; objectArray[0] = "Java Programming"; objectArray[1] = new Integer(8); objectArray[2] = new Character('z'); objectArray[3] = new Integer(4);This is the same as the very first example in this post.
Object[] thisIsAObjectArray = {"Java Code", new Integer(4)};This code will create an array with size 2 and the first item is a String with value "Java Code" and the second item is an integer with value 4. We could add some screen output to check:
public class Test { public static void main(String[] args) { Object[] thisIsAObjectArray = {"Java Code", new Integer(4)}; System.out.println( thisIsAObjectArray[0] ); System.out.println( thisIsAObjectArray[1] ); } }The output of the code should be:
Java Code 4
public class Test { public static void main(String[] args) { Object[] thisIsAObjectArray; int x = 1; x++; thisIsAObjectArray = new Object[] { "Java Code", new Integer(4) }; System.out.println(thisIsAObjectArray[0]); System.out.println(thisIsAObjectArray[1]); } }Here we did some operation on a variable x before we created an instance of object array and assign it to thisIsAObjectArray variable. The difference is that we need to add the code "new Object[]", instead of just the curly braces.