Java One-Mark and Two-Mark Questions with Answers
One-Mark Answers:
1. A constructor is a special method used to initialize objects.
2. The keyword this refers to the current object.
3. Method overloading allows multiple methods with the same name but different parameters.
4. Method overriding allows a subclass to provide a specific implementation of a method.
5. Variables declared inside a method have local scope.
6. A method that calls itself is called a recursive method.
7. Constructors do not have a return type.
8. We use the keyword this() to call one constructor from another in the same class.
9. Static methods cannot be overridden.
10. Class-level variables are also known as instance variables.
Two-Mark Answers and Explanations:
1. The method 'void Demo()' is not a constructor because it has a return type. Remove 'void':
Corrected:
Demo() {
[Link]("Constructor");
2. Method Overloading Example:
int add(int a, int b) { return a + b; }
double add(double a, double b, double c) { return a + b + c; }
3. Output: Derived
Because method call is resolved at runtime (runtime polymorphism).
4. Recursive sum of digits:
int sumDigits(int n) {
if(n == 0) return 0;
return n % 10 + sumDigits(n / 10);
5. Error: variable y is not in scope outside if block.
Fix: declare y before if block:
int y = 0;
if(x > 5) y = 20;
6. Constructor using 'this':
class Student {
int roll;
String name;
Student(int roll, String name) {
[Link] = roll;
[Link] = name;
7. Output: 5
Because 'this.x' refers to instance variable, not local one.
8. Output: 24
Because fun(4) = 4*3*2*1*1 = 24 (factorial of 4)