Given: 11. public class Ball { 12. public enum Color { RED, GREEN, BLUE }; 13. public void foo() { 14. // insert code here 15. { System.out.println(c); } 16. } 17. } Which code inserted at line 14 causes the foo method to print RED, GREEN, and BLUE?

  1. for( Color c : Color.values())

  2. for( Color c = RED; c <= BLUE; c++)

  3. for( Color c; c.hasNext() ; c.next())

  4. for( Color c = Color[0]; c <= Color[2]; c++)


Correct Option: A
Explanation:

To solve this question, the user needs to know how to iterate through an enum in Java.

Option A is correct because it uses the values() method provided by the Color enum to iterate through all the possible values, and prints each one to the console.

Option B is incorrect because it treats the Color enum as if it were an integer, which it is not. It also uses an incorrect syntax for the for loop header.

Option C is incorrect because there is no hasNext() method for enums in Java. This is a method provided by the Iterator interface, which enums do not implement.

Option D is incorrect because there is no Color[0] syntax in Java. Additionally, the enum values are not guaranteed to be stored in an array in the order they are defined.

Therefore, the correct answer is:

The Answer is: A. for( Color c : Color.values())

Find more quizzes: