QuestionQ53

Controlling Program Flow

Consider the following code fragment:

Question Image

Which action allows the code to compile?

  • A Declare grade at line 5 instead of line 7.
  • B Replace line 11 with:Predicate pred = grade -> grade == 2;
  • C Declare g at line 5.
  • D At line 12, replace pred.test(grade) with pred.test(g).
Explanation

A local variable declared within a block is in scope only for the remainder of that block. Declaring int grade = 1; at line 5 places grade in the method block, where it is visible to both the else if block and the println statement; its initializer also ensures it is definitely assigned before use. Java Language Specification, Chapter 6: Names

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!