🧠 Quick Study Guide: Accessing Java Array Elements
- 📚 Arrays are ordered collections of elements of the same data type.
- 💡 In Java, arrays are objects, even for primitive types.
- 🔢 Array elements are accessed using an index, which is an integer.
- 🎯 Indexing in Java arrays is 0-based, meaning the first element is at index 0, the second at index 1, and so on.
- 🔚 The last element of an array of size N is at index N-1.
- ⚠️ Attempting to access an element outside this range (e.g., negative index or index $\ge N$) results in an
ArrayIndexOutOfBoundsException at runtime.
- 📏 The
length property (e.g., myArray.length) gives the number of elements in the array.
📝 Practice Quiz: Java Array Access
Choose the best option for each question.
-
What is the index of the first element in a Java array?
A) 1
B) 0
C) -1
D) Depends on the array size
-
If you declare an array
int[] numbers = {10, 20, 30, 40};, how would you access the value 30?
A) numbers[3]
B) numbers[2]
C) numbers[4]
D) numbers.get(2)
-
What happens if you try to access
myArray[myArray.length]?
A) The last element of the array is returned.
B) A compilation error occurs.
C) An ArrayIndexOutOfBoundsException is thrown at runtime.
D) The program returns null.
-
Which of the following statements correctly declares an array of 5 integers and accesses its third element?
A) int arr[5]; arr[2];
B) int[] arr = new int[5]; arr[3];
C) int[] arr = new int[5]; arr[2];
D) int arr[] = {1,2,3,4,5}; arr[5];
-
Consider the code snippet:
String[] names = {"Alice", "Bob", "Charlie"};. What will be the output of System.out.println(names[0] + " " + names[2]);?
A) Alice Bob
B) Alice Charlie
C) Bob Charlie
D) Error
-
What is the purpose of the
length property when working with arrays in Java?
A) To get the capacity of the array in bytes.
B) To determine the maximum index that can be used.
C) To get the number of elements currently stored in the array.
D) To resize the array dynamically.
-
Which of these is NOT a valid way to initialize and access an array element in Java?
A) int[] arr = new int[3]; arr[0] = 5;
B) int[] arr = {1, 2, 3}; System.out.println(arr[1]);
C) int arr[]; arr = new int[2]; System.out.println(arr[0]);
D) int arr[] = new int[4]; arr[4] = 10;
Click to see Answers
1. B
2. B
3. C
4. C
5. B
6. C
7. D