What is the output of the following code? public class ex { public static void…
2024
What is the output of the following code? public class ex { public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5}; print(a); } public static void print(int[] a) { for(int n : a) { System.out.print(n + " "); } } }
- A.
Compilation error
- B.
5 4 3 2 1
- C.
Runtime error
- D.
1 2 3 4 5
- E.
Question not attempted
Attempted by 109 students.
Show answer & explanation
Correct answer: D
Step 1: The code defines a class 'ex' with a main method and a print method.
Step 2: In main(), an integer array 'a' is initialized with values {1, 2, 3, 4, 5}.
Step 3: The print() method is called with the array 'a' as argument.
Step 4: Inside print(), a for-each loop iterates over each element of the array in order.
Step 5: For each element, the value is printed followed by a space.
Step 6: The loop prints 1 2 3 4 5 in sequence, with a space after each number.