Bird
0
0

What will be the output of this Java code?

medium📝 Predict Output Q5 of 15
Java - Encapsulation
What will be the output of this Java code?
class Account {
  private double balance = 1000;
  public double getBalance() { return balance; }
  public void setBalance(double balance) { this.balance = balance; }
}
public class Test {
  public static void main(String[] args) {
    Account acc = new Account();
    acc.setBalance(500);
    System.out.println(acc.getBalance());
  }
}
A1000.0
B500.0
CCompilation error
D0.0
Step-by-Step Solution
Solution:
  1. Step 1: Understand setter and getter usage

    Setter updates the private balance to 500, getter returns updated value.
  2. Step 2: Trace method calls in main

    acc.setBalance(500) sets balance to 500, then acc.getBalance() returns 500.
  3. Final Answer:

    500.0 -> Option B
  4. Quick Check:

    Setter updates value, getter returns updated value [OK]
Quick Trick: Set value with setter, get updated value with getter [OK]
Common Mistakes:
  • Expecting original value instead of updated
  • Confusing direct access with method access
  • Assuming compilation error due to private variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes