Syntax error How to convert an object array to an integer array in Java?

How to convert an object array to an integer array in Java?



You can convert an object array to an integer array in one of the following ways −

  • By copying each element from integer array to object array −

Example

import java.util.Arrays;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Object[] objArray = {21, 58, 69, 33, 65};
      int length = objArray.length;
      int intArray[] = new int[length];
      for(int i=0; i<length; i++){
         intArray[i] = (int) objArray[i];
      }
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
   }
}

Output

Contents of the integer array: [21, 58, 69, 33, 65]
  • Using the arrayCopy() method of the System class −

Example

import java.util.Arrays;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Object[] objArray = {21, 58, 69, 33, 65};
      int length = objArray.length;
      Integer intArray[] = new Integer[length];
      System.arraycopy(objArray, 0, intArray, 0, length);
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
   }
}

Output

Contents of the integer array: [21, 58, 69, 33, 65]
  • Using the copyOf() method of the arrays class −

Example

import java.util.Arrays;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Object[] objArray = {21, 58, 69, 33, 65};
      int length = objArray.length;
      Integer[] intArray = Arrays.copyOf(objArray, length, Integer[].class);
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
   }
}

Output

Contents of the integer array: [21, 58, 69, 33, 65]
  • Using the toArray() method of the List class −

Example

import java.util.Arrays;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Object[] objArray = {21, 58, 69, 33, 65};
      Integer[] intArray = Arrays.asList(objArray).toArray(new Integer[0]);
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
   }
}

Output

Contents of the integer array: [21, 58, 69, 33, 65]
Updated on: 2019-07-30T22:30:26+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements