Java Arrays Cheat Sheet
Creating Arrays
Java
Copy
int[] arr1; int[] arr2 = {1, 2, 3, 4}; int[] arr3 = new int[]{1, 2, 3, 4, 5}; int[] arr4 = new int[4]; arr4[0] = 1; arr4[2] = 2; arr4[3] = 3; arr4[4] = 4;
Modifying Array
Java
Copy
int[] arr = new int[]{1, 2, 3, 4, 5}; System.out.println(arr[3]); // 4 System.out.println(arr[4]); // 5 arr[4] = 1; arr[3] = 2; System.out.println(arr[3]); // 2 System.out.println(arr[4]); // 1
Loop Through an Array
Using for loop
Java
Copy
String[] fruits = {"Apple", "Orange", "Grapes", "Mango"}; for (int i = 0; i < fruits.length; i++) { System.out.println(fruits[i]); }
Using foreach loop
Java
Copy
String[] fruits = {"Apple", "Orange", "Grapes", "Mango"}; for (String fruit : fruits) { System.out.println(fruit); }
Multidimensional Arrays
Java
Copy
int[][] arr1 = new int[2][2]; // 2 row and 2 column arr1[0][0] = 1; arr1[0][1] = 2; arr1[1][0] = 3; arr1[1][1] = 4; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { System.out.print(arr1[i][j] + " "); // 1 2 3 4 } } System.out.println(); int[][] arr2 = {{1, 2, 3}, {2, 4, 5}, {4, 4, 5}}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(arr2[i][j] + " "); // 1 2 3 2 4 5 4 4 5 } }
Arrays Methods
Java
Copy
int[] arr1 = {3,5,1,2,8,6}; int[] arr2 = {1,2,3,5,6,8}; int[] arr3 = new int[3]; //Printing an array System.out.println(Arrays.toString(arr1)); // [3, 5, 1, 2, 8, 6] // Sorting an array Arrays.sort(arr1); System.out.println(Arrays.toString(arr1)); // [1, 2, 3, 5, 6, 8] //Compares two int arrays lexicographically. System.out.println(Arrays.compare(arr1, arr2)); // 0 // Returns true if the two specified arrays of ints are equal to one another System.out.println(Arrays.equals(arr1, arr2)); // true // Assigns the specified int value to each element of the specified array of ints. Arrays.fill(arr3, 1); System.out.println(Arrays.toString(arr3)); // [1, 1, 1] //Copies the specified array arr3 = Arrays.copyOf(arr1,4); System.out.println(Arrays.toString(arr3)); // [1, 2, 3, 5]