JAVA Topic 4: Arrays
You can declare, create and initialize array in one step
double [ ] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement
Finding the largest element
double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myLIst[i]; }
declaring array variables
datatype[ ] arrayRefVar; e.g. double [ ] myList;
Ragged arrays
Each for in a two dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as ragged array. For example, int [ ] [ ] matrix = { {1, 2, 3, 4, 5,}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} },
The arraycopy utility making source array equal to target array
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
Once an array is created, its size cannot be changed.
You can find the size of an array using arrayRefVar.length e.g. myList.length returns 10
Creating arrays
arrayRefVar = new datatype [arraySize]; e.g. myList = new double [10] myList [0] references the first element in the array myList [0] references the last element in the array
Initializing arrays with input values
java.util.Scanner input = new java.util.Scanner (System.in); System.out.print("Enter" + myList.length + "values: "); for (int i = 0; i < myList.length; i++) myList[i] = input.nextDouble();