Java Arrays and ArrayLists: Essential Concepts and Fixes
Section 1: Java Array Fundamentals
- An array is a collection of elements of the same data type stored in one variable.
- The index of the first element is 0.
- The correct declaration is:
int[] arr = new int[5]; - The size of the array is 10.
- The best loop for arrays is a
forloop. - A 2D array represents a table.
ArrayListbelongs tojava.util.ArrayListcan store objects.- The method used to add an element is
add(). arr.lengthgives the size of the array.
Section 2: Array Properties
- Arrays store elements of the same type.
- The last index of an array of size n is n - 1.
- A 2D array is also called a two-dimensional array.
ArrayListsize can grow dynamically.- The loop used to traverse arrays is usually a
forloop.
Section 3: Advanced Array Concepts
- A 1D array is a list of elements of the same data type stored in a single row using one index.
- An array has a fixed size, while an
ArrayListcan change size dynamically. - Indexing is the position number used to access elements in an array.
- A real-life example of a 2D array is a spreadsheet with rows and columns.
- Arrays are fixed in size because memory is allocated when they are created.
Section 4: Debugging Common Java Errors
- Code:
int arr = new int[5];
Error: The array is missing square brackets. It should be written asint[] arr = new int[5];. - Code:
for(int i = 1; i <= 5; i++){ System.out.println(arr[i]); }
Error: The loop starts at index 1 and goes to 5, which goes out of bounds. Arrays start at 0 and end at 4. - Code:
ArrayList list = new ArrayList(); list.add(10); System.out.println(list.get(1));
Error: Only one element was added, so index 1 does not exist. The correct index is 0. - Code:
int arr[] = {1,2,3}; System.out.println(arr[3]);
Error: Index 3 is out of bounds. The last index is 2. - Code:
int[][] arr = new int[2][3]; arr[2][1] = 5;
Error: Row index 2 is out of bounds. The valid row indexes are 0 and 1. - Code:
int arr[] = new int[5]; for(int i = 0; i < ____; i++){ arr[i] = i; }
Answer:arr.length - Code:
ArrayList list = new ArrayList<>(); list.____(10);
Answer:add - Code:
int[][] arr = new int[2][2]; arr[0][0] = 5; arr[0][1] = __;
Answer: 10 - Code:
for(int i = 0; i < arr.length; i++){ System.out.println(____); }
Answer:arr[i] - Code:
ArrayList names = new ArrayList<>(); System.out.println(names.____());
Answer:size()
English with a size of 3.32 KB