Java OCA OCP Practice Question 1786

Question

Which of the following implementations of a max() method will correctly return the largest value?.

// (1)//w  w  w . j  ava 2  s . c  o m
int max(int x, int y) {
  return (if (x > y) { x; } else { y; });
}

// (2)
int max(int x, int y) {
  return (if (x > y) { return x; } else { return y; });
}

// (3)
int max(int x, int y) {
  switch (x < y) {
    case true:
      return y;
    default:
      return x;
  };
}

// (4)
int max(int x, int y) {
  if (x>y) return x;
  return y;
}

Select the one correct answer.

  • (a) Implementation labeled (1).
  • (b) Implementation labeled (2).
  • (c) Implementation labeled (3).
  • (d) Implementation labeled (4).


(d)

Note

Implementation (4) will correctly return the largest value.

The if statement does not return any value and, therefore, cannot be used as in implementations (1) and (2).

Implementation (3) is invalid since neither the switch expression nor the case label values can be of type boolean.




PreviousNext

Related