Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Encapsulation
What will be the output of this code?
public class Student {
  private int age;
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public static void main(String[] args) {
    Student s = new Student();
    System.out.println(s.getAge());
  }
}
A0
Bnull
CCompilation error
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand default value of int

    Private int variable age defaults to 0 if not set.
  2. Step 2: Getter returns age

    Since setAge was not called, getAge returns 0.
  3. Final Answer:

    0 -> Option A
  4. Quick Check:

    Default int value = 0 [OK]
Quick Trick: Uninitialized int defaults to 0 in Java [OK]
Common Mistakes:
  • Expecting null for int
  • Assuming compilation error without setter call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes