0
0
Javaprogramming~5 mins

This keyword usage in Java - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the this keyword refer to in Java?
The <code>this</code> keyword refers to the current object instance of the class where it is used. It helps to access instance variables and methods.
Click to reveal answer
beginner
How do you use this to distinguish between instance variables and parameters with the same name?
You use this.variableName to refer to the instance variable, while the parameter is accessed by its name alone. This avoids confusion when names overlap.
Click to reveal answer
intermediate
Can this be used to call another constructor in the same class? How?
Yes, this() can be used to call another constructor in the same class. It must be the first statement in the constructor calling it.
Click to reveal answer
beginner
Is it possible to use this in a static method? Why or why not?
No, this cannot be used in static methods because static methods belong to the class, not to any specific object instance.
Click to reveal answer
intermediate
What happens if you omit this when instance variables are shadowed by parameters?
If you omit this, the parameter variable will be used instead of the instance variable, which can cause bugs because the instance variable won't be updated.
Click to reveal answer
What does this refer to inside a Java instance method?
AThe superclass
BThe class itself
CA static variable
DThe current object instance
How do you call another constructor in the same class using this?
Athis(); as the first statement in the constructor
Bsuper(); inside the constructor
Cthis.callConstructor(); anywhere in the constructor
DYou cannot call another constructor with <code>this</code>
Can you use this inside a static method?
ANo, because static methods do not belong to an instance
BYes, always
COnly if the static method is public
DOnly if the static method is called from an instance
Why use this.variable inside a constructor?
ATo access a superclass method
BTo call a static method
CTo refer to the instance variable when a parameter has the same name
DTo create a new object
What happens if you forget to use this when setting an instance variable with a parameter of the same name?
AThe program throws an error
BThe parameter value is assigned to itself, instance variable remains unchanged
CThe instance variable is updated correctly
DThe compiler automatically adds <code>this</code>
Explain how the this keyword helps when constructor parameters have the same names as instance variables.
Think about how to tell Java you mean the object's variable, not the parameter.
You got /4 concepts.
    Describe why this cannot be used inside static methods in Java.
    Consider what <code>this</code> means and what static means.
    You got /4 concepts.