What is an array in Java?
A
A data structure that holds multiple values of different types B
A variable that stores multiple values of the same type C
A class for string operations D
A method that sorts values
Analysis & Theory
An array is a container object that holds a fixed number of values of the same type.
How do you declare an array of integers in Java?
A
int array = new int(); B
int[] array; C
array[] int; D
int array[] = int();
Analysis & Theory
Correct syntax: `int[] array;` declares an integer array.
What is the index of the first element in a Java array?
A
1 B
0 C
-1 D
Depends on array type
Analysis & Theory
Java arrays are zero-indexed. The first element is at index 0.
How do you initialize an array with values in Java?
A
int[] arr = {1, 2, 3}; B
int arr = [1, 2, 3]; C
array arr = new array(1, 2, 3); D
int arr[] = new int[3]{1, 2, 3};
Analysis & Theory
Correct syntax: `int[] arr = {1, 2, 3};` initializes an array with values.
What is the output?
```java
int[] arr = {10, 20, 30};
System.out.println(arr[1]);```
A
10 B
20 C
30 D
1
Analysis & Theory
`arr[1]` accesses the second element, which is 20.
What happens if you try to access an array index out of bounds?
A
Returns -1 B
Returns null C
Throws ArrayIndexOutOfBoundsException D
Wraps around to start of array
Analysis & Theory
Accessing invalid indexes throws `ArrayIndexOutOfBoundsException`.
Which method gives the number of elements in an array?
A
arr.length() B
arr.size() C
arr.length D
arr.count()
Analysis & Theory
Use `arr.length` (without parentheses) to get the size of a Java array.
What is the output?
```java
int[] arr = new int[3];
System.out.println(arr[0]);```
A
0 B
null C
undefined D
Compilation error
Analysis & Theory
Integer arrays are initialized with 0 by default in Java.
How can you iterate through all elements of an array?
A
Using a `for` or `for-each` loop B
Using a `while` loop only C
Only with streams D
Arrays cannot be looped
Analysis & Theory
You can use `for`, `for-each`, `while`, or streams to iterate through arrays.
Which of these is a correct enhanced for loop syntax?
A
for(int i : arr) { } B
for(i in arr) { } C
foreach i in arr { } D
for i in arr: { }
Analysis & Theory
Correct Java enhanced for-loop syntax: `for(int i : arr) { }`