Java OCA OCP Practice Question 3213

Question

Given the following program:

public class Main {
  public static void main(String[] args) {
    String str = "loop or not to loop";
    String[] strs = {"loop", "or", "not", "to", "loop"};
    // (1) INSERT LOOP HERE.
  }
}

Which code, when inserted at (1), will compile without errors?

Select the four correct answers.

(a) for (char ch : str)
      System.out.print(ch);/*from  w ww.j  a v  a2 s.c  o m*/
(b) for (char ch : str.toCharArray())
      System.out.print(ch);
(c) for (Character ch : str.toCharArray())
      System.out.print(ch);
(d) for (Character ch : str.toCharArray())
      System.out.print(ch.charValue());

(e) for (String str : strs)
      System.out.print(str);
(f) for (String elt : strs[])
      System.out.print(elt);
(g) for (String elt : strs)
      System.out.print(elt);
(h) for (Character ch : strs[str.length-1].toArray())
      System.out.print(ch);


(b), (c), (d), (g)

Note

In (a), a String is neither an array nor an Iterable.

In (e), the local variable str is redeclared.

In (f) the occurrence of the array operator [] is not permissible.

In (h), the String class does not have a method called toArray, but it has a method called toCharArray().




PreviousNext

Related