how can I declare an Object Array in Java?

Java 8Object Oriented ProgrammingProgramming

Array of Object class can be created which can accept any type of object. During operation on such array, instanceof operator can be used.

Example

public class Tester {
   public static void main(String[] args) {
      Object[] dataArray = new Object[3];
      dataArray[0] = new Integer(0);
      dataArray[1] = new String("1");
      dataArray[2] = new Boolean(false);
      for(Object data: dataArray) {
         if(data instanceof Integer) {
            System.out.println(((Integer) data).intValue());
         }
         if(data instanceof String) {
            System.out.println(data);
         }
         if(data instanceof Boolean) {
            System.out.println(((Boolean) data).booleanValue());
         }
      }
   }
}

Output

0
1
false
raja
Published on 06-Feb-2018 10:56:28
Advertisements