What is the purpose of the 'this' keyword in Java?
ATo refer to the parent class
BTo refer to the current object instance
CTo create a new object
DTo access static variables
Correct Answer:
B. To refer to the current object instance
EXPLANATION
'this' is a reference variable that refers to the current object instance. It is used to distinguish instance variables from local variables with the same name, or to pass the current object as a parameter.
Which keyword is used to create a constant variable in Java that cannot be modified after initialization?
Astatic
Bconst
Cfinal
Dimmutable
Correct Answer:
C. final
EXPLANATION
The 'final' keyword is used to declare constants in Java. Once a final variable is assigned a value, it cannot be changed. 'const' is a reserved keyword but not used in Java.
What will be the output? class Test { public static void main(String[] args) { int x = 10; { int x = 20; System.out.println(x); } System.out.println(x); } }
A10 20
B20 10
C20 20
DCompilation Error
Correct Answer:
B. 20 10
EXPLANATION
A block scope creates a new variable x = 20 which shadows the outer x. First print outputs 20, then the block ends, outer x (10) is printed.