Java OCA OCP Practice Question 1792

Question

Which method declarations, when inserted at (1), will result in the program compiling and printing 90 when run?.

public class Main {
  public static void main(String[] args) {
    doIt();
  }
  // (1) INSERT METHOD DECLARATION HERE.
}

Select the two correct answers.

(a) public static void doIt() {
      int[] nums = {20, 30, 40};
      for (int sum = 0, i : nums)
        sum += i;/*from w  ww  .  j  a  v a 2s.  c  o  m*/
      System.out.println(sum);
    }
(b) public static void doIt() {
      for (int sum = 0, i : {20, 30, 40})
        sum += i;
      System.out.println(sum);
    }

(c) public static void doIt() {
      int sum = 0;
      for (int i : {20, 30, 40})
        sum += i;
      System.out.println(sum);
    }
(d) public static void doIt() {
      int sum = 0;
      for (int i : new int[] {20, 30, 40})
        sum += i;
      System.out.println(sum);
    }
(e) public static void doIt() {
      int[] nums = {20, 30, 40};
      int sum = 0;
      for (int i : nums)
        sum += i;
      System.out.println(sum);
    }


(d) and (e)

Note

In the header of a for(:) loop, we can only declare a local variable that is compatible with the element type of an Iterable or an array.

This rules out (a) and (b).

The Iterable or array can be specified by an expression that evaluates to a reference type of an Iterable or an array.

It is only evaluated once.

Expressions that are permissible are found in (a), (d), and (e), but only (d) and (e) specify a legal for(:) header.




PreviousNext

Related