Given the code fragment:
What is the result?
Given the code fragment:
What is the result?
B
To test: public static void main(String[] args) { int sum = 0; for (int xVal = 1; xVal <= 5; xVal++) { sum = sum + xVal; } System.out.println("The sum of " + xVal + " numbers is: " + sum); }
answer is B: "A compile time error occurs." xVal - is unreachable outside FOR loop
The correct answer is the letter B, it is the typical case of differentiating between local variable and instance variable, as the local variable "xVal" was instantiated inside the for, the code inside the for compiles normally, but when exiting for and trying printing the variable inside the class cannot because there is no variable created with that name, as "xValr" is a local variable, its instantiation is only valid locally inside the for and not outside it.