1Z0-808 · Question #31
public class App { String myStr = "7007"; public void doStuff(String str) { int myNum = 0; try { String myStr = str; myNum = Integer.parseInt(myStr); } catch (NumberFormatException ne) {…
The correct answer is C. myStr: 7007, myNum: 9009. Option C is correct because of variable scoping: the local String myStr = str is declared inside the try block, so it only exists within that block's scope. When System.out.println executes outside the try block, Java resolves myStr to the instance variable "7007", not the…
Question
Options
- AmyStr: 9009, myNum: 9009
- BmyStr: 7007, myNum: 7007
- CmyStr: 7007, myNum: 9009
- DCompilation falls
How the community answered
(33 responses)- A12% (4)
- B3% (1)
- C76% (25)
- D9% (3)
Explanation
Option C is correct because of variable scoping: the local String myStr = str is declared inside the try block, so it only exists within that block's scope. When System.out.println executes outside the try block, Java resolves myStr to the instance variable "7007", not the local one. myNum, however, is declared outside the try block and gets successfully assigned Integer.parseInt("9009") = 9009, so it prints as 9009.
- A is wrong because
myStrin the print statement resolves to the instance variable"7007", not the local"9009". - B is wrong because
myNumis correctly parsed from"9009"and assigned9009, not7007. - D is wrong because the code compiles fine - shadowing an instance variable with a local one is legal in Java.
Memory tip: When you see a variable declared inside a block (try, if, for), it dies when that block closes - the outer scope's variable with the same name "comes back to life" for any code that follows.
Topics
Community Discussion
No community discussion yet for this question.