nerdexam
Oracle

1Z0-803 · Question #253

Given the code fragment? public class Test { public static void main(String[] args) { Test t = new Test(); int[] arr = new int[10]; arr = t.subArray(arr,0,2); } // insert code here } Which method can

The correct answer is A. public int[] subArray(int[] src, int start, int end) {. This question tests understanding of Java method signatures, specifically return types and parameter types, to ensure proper compilation based on a method call. The inserted method must match the return type int[] and parameter types int[], int, int used in the calling statement.

Working with Methods and Encapsulation

Question

Given the code fragment? public class Test { public static void main(String[] args) { Test t = new Test(); int[] arr = new int[10]; arr = t.subArray(arr,0,2); } // insert code here } Which method can be inserted at line // insert code here to enable the code to compile?

Options

  • Apublic int[] subArray(int[] src, int start, int end) {
  • Bpublic int subArray(int src, int start, int end) {
  • Cpublic int[] subArray(int src, int start, int end) {
  • Dpublic int subArray(int[] src, int start, int end) {

How the community answered

(38 responses)
  • A
    92% (35)
  • C
    3% (1)
  • D
    5% (2)

Why each option

This question tests understanding of Java method signatures, specifically return types and parameter types, to ensure proper compilation based on a method call. The inserted method must match the return type `int[]` and parameter types `int[], int, int` used in the calling statement.

Apublic int[] subArray(int[] src, int start, int end) {Correct

The method call `t.subArray(arr,0,2)` expects a method named `subArray` that takes an `int[]`, an `int`, and another `int` as parameters, and returns an `int[]` to be assigned to `arr`. Option A provides exactly this signature, allowing the code to compile.

Bpublic int subArray(int src, int start, int end) {

This method is incorrect because it returns an `int` instead of an `int[]` and its first parameter is `int` instead of `int[]`, leading to a compilation error.

Cpublic int[] subArray(int src, int start, int end) {

This method is incorrect because its first parameter is `int` instead of `int[]`, which does not match the `arr` (an `int[]`) passed in the method call.

Dpublic int subArray(int[] src, int start, int end) {

This method is incorrect because it returns an `int` instead of an `int[]`, which cannot be assigned back to the `arr` variable of type `int[]`.

Concept tested: Java method signatures and parameter matching

Source: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

Topics

#method signature#return types#parameters#arrays

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice