1Z0-811 1Z0-811 Java Methods and Scope 2 — Questions and Answers
Question 1: What is the purpose of the `this` keyword inside an instance method?
- It refers to the parent class
- It refers to the current object instance (Correct answer)
- It refers to a static field
- It calls a superclass constructor
Correct answer: It refers to the current object instance
The `this` keyword refers to the current instance of the class and is used to access its fields and methods.
Question 2: Which access modifier restricts a method's visibility to the same class only?
- public
- protected
- default
- private (Correct answer)
Correct answer: private
The `private` access modifier makes a method accessible only within the class in which it is declared.
Question 3: Can a `static` method access instance variables directly?
- Yes, always
- Yes, but only if the instance variable is final
- No, because static methods belong to the class, not an instance (Correct answer)
- Yes, if the variable is declared public
Correct answer: No, because static methods belong to the class, not an instance
Static methods do not have access to instance variables directly because they are not associated with any object instance.
Question 4: Which of the following is true about variable shadowing in Java?
- It occurs when a local variable has the same name as an instance variable (Correct answer)
- It only occurs with static variables
- It causes a compilation error
- It only applies to primitive types
Correct answer: It occurs when a local variable has the same name as an instance variable
Variable shadowing occurs when a local variable or parameter has the same name as an instance variable, hiding the instance variable within that scope.
Question 5: What is the difference between pass-by-value and pass-by-reference in the context of Java method arguments?
- Java uses pass-by-reference for all types
- Java uses pass-by-value; for objects, the reference value (address) is passed (Correct answer)
- Java uses pass-by-reference for objects and pass-by-value for primitives
- Java uses pass-by-value only for String types
Correct answer: Java uses pass-by-value; for objects, the reference value (address) is passed
Java always passes arguments by value; for object types, the value passed is the reference (memory address) of the object, not the object itself.
Question 6: Which of the following correctly declares a varargs parameter in a method?
- public void print(String[] ...args)
- public void print(String... args) (Correct answer)
- public void print(varargs String args)
- public void print(*String args)
Correct answer: public void print(String... args)
Varargs is declared using an ellipsis (`...`) after the type, allowing a method to accept zero or more arguments of that type.
What is the purpose of the `this` keyword inside an instance method?