Which of the statements given below are true?
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Which of the statements given below are true?
I) this keyword can be used to refer current class instance variable.
II) this() can be used to invoke current class constructor.
III) this keyword can be used to invoke current class method (implicitly).
IV) this can be passed as an argument in the method call.
V) this can be passed as argument in the constructor call.
VI) this keyword can also be used to return the current class instance.
Show answer & explanation
All six statements about the this keyword in Java are correct. The this keyword is a reference to the current object instance and can be used to access instance variables (I), invoke constructors via this() (II), implicitly call methods (III), pass the current object as an argument to methods (IV) or constructors (V), and return the current instance from a method (VI). Each usage is a valid and common Java programming pattern.
Step-by-step Derivation:
Verification of each statement:
I) TRUE - this.variableName accesses instance variables:
class Example {
int x = 5;
void method() {
System.out.println(this.x); // Refers to instance variable
}
}
II) TRUE - this() invokes the current class constructor:
class Example {
Example() {
this(10); // Calls overloaded constructor
}
Example(int x) {
// Constructor body
}
}
III) TRUE - this can implicitly invoke methods:
class Example {
void method1() {
this.method2(); // Or just method2();
}
void method2() {}
}
IV) TRUE - this can be passed as method argument:
class Example {
void passThis() {
someMethod(this); // Pass current object
}
void someMethod(Example obj) {}
}
V) TRUE - this can be passed as constructor argument:
class Example {
Example() {
new AnotherClass(this); // Pass current instance
}
}
class AnotherClass {
AnotherClass(Example e) {}
}
VI) TRUE - this can return the current instance:
class Example {
Example getThis() {
return this; // Return current object
}
}
Conclusion: All six statements (I-VI) are valid uses of the this keyword. Answer is A.