nerdexam
Oracle

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…

Java Basics

Question

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) { System.err.println("Error"); } System.out.println( "myStr: " + myStr + ", myNum: " + myNum); } public static void main(String[] args) { App obj = new App(); obj.doStuff("9009"); } } What is the result?

Options

  • AmyStr: 9009, myNum: 9009
  • BmyStr: 7007, myNum: 7007
  • CmyStr: 7007, myNum: 9009
  • DCompilation falls

How the community answered

(33 responses)
  • A
    12% (4)
  • B
    3% (1)
  • C
    76% (25)
  • D
    9% (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 myStr in the print statement resolves to the instance variable "7007", not the local "9009".
  • B is wrong because myNum is correctly parsed from "9009" and assigned 9009, not 7007.
  • 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

#Variable shadowing#Variable scope#try-catch blocks#Scope resolution

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice