What is the output of the following JAVA program? class simple { public static…
2018
What is the output of the following JAVA program?
class simple { public static void main(String[ ] args) { simple obj = new simple(); obj.start(); } void start() { long [] P = {3, 4, 5}; long [] Q = method (P); System.out.print (P[0] + P[1] +P[2]+”:”); System.out.print (Q[0] + Q[1] + Q[2]); } long [ ] method (long [ ] R) { R[1] = 7; return R; } } //end of class- A.
12:15
- B.
15:12
- C.
12:12
- D.
15:15
Attempted by 45 students.
Show answer & explanation
Correct answer: D
Answer: 15:15
Explanation: The method receives a reference to the array, so modifying the array inside the method affects the original array.
Initial array P is {3, 4, 5}.
The method sets R[1] = 7. Since R refers to P, P becomes {3, 7, 5}.
Q receives the returned reference, so Q refers to the same array {3, 7, 5}.
Sum of elements in P is 3 + 7 + 5 = 15; sum of elements in Q is also 15. The prints produce "15:" then "15" resulting in 15:15.
A video solution is available for this question — log in and enroll to watch it.