Can you assign an Array of 100 elements to an array of 10 elements in Java?


In general, arrays are the containers that store multiple variables of the same datatype. These are of fixed size and the size is determined at the time of creation. Each element in an array is positioned by a number starting from 0.

You can access the elements of an array using name and position as −

System.out.println(myArray[3]);
//Which is 1457

Creating an array in Java

In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −

int myArray[] = new int[7];

While creating array in this way, you must specify the size of the array.

You can also directly assign values within flower braces separating them with commas (,) as −

int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524};

Assigning larger array to a smaller one

Yes, you can assign an array with 100 elements to an array of size 10 provided they are of same type.

While assigning the compiler doesn’t bother the sizes it just verifies the type of both arrays and proceeds further.

Example

import java.util.Arrays;
public class Test {
   public static void main(String[] args) {
      int[] intArray = new int[100];
      for(int i=0; i<100; i++) {
         intArray[i] = i;
      }
      System.out.println(Arrays.toString(intArray));
   }
}

Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99]

Updated on: 02-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements