how to array java code example

Example 1: creating array java

int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }

Example 2: how to create an array in java

int[] array1 = new int[5]; //int array length 5
String[] array2 = new String[5] //String array length 5
double[] array3 = new double[5] // Double array length 5

Example 3: java array

// ! IMPORTANTE !
// in JAVA an array is not the same as an ArrayList object!!
// 1 - declare, instanciate and populate
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
// 2 - declare and instanciate an int array with maxSize
// note: the index goes between 0 and maxSize-1
int newarr[] = new int[maxSize];
// 2.1 - insert the value n on the position pos
newarr[pos] = n; 
// 2.2 - insert values recursively
for (i = 0; i < maxSize; i++) { newarr[i] = arr[i]; }

Example 4: arrays in java

int[] intArray = new int[20];
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Example 5: arrays in java

int[] arr;			// Declaration dataType can int, float etc.
arr = new int[N];	// Allocation N = 0 to 2,147,483,647.