Java Arrays and ArrayLists: Essential Concepts and Fixes

Posted by Anonymous and classified in Computers

Written on in English with a size of 3.32 KB

Section 1: Java Array Fundamentals

  1. An array is a collection of elements of the same data type stored in one variable.
  2. The index of the first element is 0.
  3. The correct declaration is: int[] arr = new int[5];
  4. The size of the array is 10.
  5. The best loop for arrays is a for loop.
  6. A 2D array represents a table.
  7. ArrayList belongs to java.util.
  8. ArrayList can store objects.
  9. The method used to add an element is add().
  10. arr.length gives the size of the array.

Section 2: Array Properties

  1. Arrays store elements of the same type.
  2. The last index of an array of size n is n - 1.
  3. A 2D array is also called a two-dimensional array.
  4. ArrayList size can grow dynamically.
  5. The loop used to traverse arrays is usually a for loop.

Section 3: Advanced Array Concepts

  1. A 1D array is a list of elements of the same data type stored in a single row using one index.
  2. An array has a fixed size, while an ArrayList can change size dynamically.
  3. Indexing is the position number used to access elements in an array.
  4. A real-life example of a 2D array is a spreadsheet with rows and columns.
  5. Arrays are fixed in size because memory is allocated when they are created.

Section 4: Debugging Common Java Errors

  1. Code: int arr = new int[5];
    Error: The array is missing square brackets. It should be written as int[] arr = new int[5];.
  2. 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.
  3. 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.
  4. Code: int arr[] = {1,2,3}; System.out.println(arr[3]);
    Error: Index 3 is out of bounds. The last index is 2.
  5. 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.
  6. Code: int arr[] = new int[5]; for(int i = 0; i < ____; i++){ arr[i] = i; }
    Answer: arr.length
  7. Code: ArrayList list = new ArrayList<>(); list.____(10);
    Answer: add
  8. Code: int[][] arr = new int[2][2]; arr[0][0] = 5; arr[0][1] = __;
    Answer: 10
  9. Code: for(int i = 0; i < arr.length; i++){ System.out.println(____); }
    Answer: arr[i]
  10. Code: ArrayList names = new ArrayList<>(); System.out.println(names.____());
    Answer: size()

Related entries: