Which of the following correctly demonstrates method overloading?
ATwo methods with same name and same parameters in different classes
BTwo methods with same name but different number or type of parameters in the same class
CTwo methods with different names and different parameters in the same class
DTwo methods with same name and return type in the same class
Correct Answer:
B. Two methods with same name but different number or type of parameters in the same class
EXPLANATION
Method overloading allows multiple methods with the same name but different parameters (number, type, or order) in the same class. This is a way to implement compile-time (static) polymorphism.
Consider the following code: int x = 5; x += 3; System.out.println(x); What is the output?
A5
B8
C53
DCompilation error
Correct Answer:
B. 8
EXPLANATION
The += operator is an assignment operator that adds the right operand to the left operand and assigns the result. So x += 3 means x = x + 3, which is 5 + 3 = 8.
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.