Wednesday 20 February 2013

9. What will be the result of executing the following code?

9. What will be the result of executing the following code?

Choices:
a. 100 will be printed 11 times.
b. 100 will be printed 10 times and then there will be a runtime exception.
c. The code will not compile because the variable i cannot be declared twice within the main() method.
d. The code will not compile because the variable j cannot be declared twice within the switch statement.
e. None of these.


Answer:-
E is correct.
The code will not compile.
There is no problem with the declaration of another variable i as both the variables are in disjoint blocks (first one is inside the for loop and its scope ends with the for loop, whereas the second is outside the for loop) and, therefore, different scopes and hence valid.
The problem is with the variable j.
The two declarations of the variable j are perfectly valid as they are in disjoint blocks and, therefore, different scopes.
The error is that both the declarations of j are not available outside the case or default statement, whereas we are trying to assign it to the variable i.
Therefore the compiler objects and reports variable j not found.

Error:-


Exception in thread "main" java.lang.Error: Unresolved compilation problem:
j cannot be resolved to a variable

No comments:

Post a Comment