When you pass it as an argument, you pass a copy of the reference to the array.
Syntax
Java style is preferred
// C-styleint array[];// Java-styleint[] array;
Creation
max size of array is slightly less than Integer.MAX_VALUE
// list of elementsint[] array = { 1, 2, 3, 4 };// n = array lengthint[] numbers = new int[n];// new keyword with list of elementsvar floatNumbers = new float[] { 1.02f, 0.03f, 4f };
Iteration
For each loop has limitations:
cannot access other indices values
cannot modify an array because the variable we use for iterations doesn’t hold the actual array element, only a copy
int[] squares = new int[5];// for-loopfor (int i = 0; i < squares.length; i++) { squares[i] = i * i; // set the value by the element index }System.out.println(Arrays.toString(squares)); // [0, 1, 4, 9, 16]// for-each loopfor (var num:squares) { num = 50; // this does not modify the array}System.out.println(Arrays.toString(squares)); // [0, 1, 4, 9, 16]
Multi-dimensional arrays
You can have jagged array with each row having different columns
int[][] twoDimArray = { {0, 0}, // the length is 2 {1, 2, 3, 4}, // the length is 4 {3, 3, 3} // the length is 3};System.out.println(foo instanceof int[][]);
Converting Arrays to ArrayList
Fixed size Array List:
Conversion allows arrays to be viewed as lists.
Conversion returns fixed size list
Adding and removing elements throw error
Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array.
Avoid Arrays.asList() since it is neither completely immutable nor mutable (since add not supported)
Use List.of() which creates immutable list
int[] arr = {1, 2, 3};var myList = Arrays.asList(arr); // mutable and can cause side effects to arrvar myList2 = List.of(arr); // immutable
Independent ArrayList:
String[] stringArray = new String[] { "A", "B", "C", "D" }; List stringList = new ArrayList<>(Arrays.asList(stringArray));
Converting ArrayList to Array
List<String> strList = new ArrayList<>();strList.add("abc");strList.add("xyz");strList.add("pqr");strList.add("mno");String[] strArr = strList.toArray(new String[strList.size()]);