Exam 1z0-829 All QuestionsBrowse all questions from this exam
Question 32

Given:

Which action enables the code to compile?

    Correct Answer: A

    To enable the code to compile, the instance variable 'name' needs to be accessible by the static method 'display()'. Since static methods cannot access instance variables directly, making the variable 'name' static resolves this issue. Therefore, replacing 'String name;' with 'static String name;' is necessary for the code to compile successfully.

Discussion
supersquaxOption: A

Correct answer is A, tested in online compiler. static methods cannot access instance variable unless they are static. That is to say: - either the "name" variable must be made static so that it can be accessed by the display() method on line 3 - or the display() method on line 3 must be made non-static (remove the static keyword) so that it can access the "name" variable Only alternative that achieves one of these two is A. Note that despite this change, i1.display("Flower") will still call the display() method on line 7. Non-static methods are allowed to access static instance variable regardless. In this case, since both "this.name" and "name" are null, "this.name += name;" will simply do "null += null;" and the result will be "nullnull".