Unit 3 Cycle 2 Day 14: Constructor Parameter Validation

Unit 3, Classes & Objects • Cycle 2
Day 14 Advanced Practice • Harder Difficulty
Focus: Constructor Parameter Validation Hard Constructor Parameter Validation

Advanced Practice Question

Format: Constructor Parameter Validation

What is the output?
public class BankAccount {
    private double balance;
    
    public BankAccount(double initial) {
        if (initial >= 0) {
            balance = initial;
        }
    }
    
    public double getBalance() {
        return balance;
    }
}

// In another class:
BankAccount b1 = new BankAccount(100);
BankAccount b2 = new BankAccount(-50);

System.out.println(b1.getBalance());
System.out.println(b2.getBalance());
Difficulty: Hard  |  Topic: Constructor Parameter Validation  |  Cycle: 2 (Advanced)
Why This Answer?

b1 is created with 100 (>= 0), so balance = 100.0. b2 is created with -50 (< 0), so the if condition fails and balance remains at its default value of 0.0.

Common Mistake
Watch Out!

Thinking an invalid parameter causes an error, or that balance would be -50.

AP Exam Strategy

Instance variables have default values (int=0, double=0.0). Constructors can use conditionals to validate parameters.

Master This Topic

This Cycle 2 HARD question tests constructor parameter validation. Review Unit 3 concepts to build mastery of classes & objects.

  • Understanding constructor parameter validation
  • Tracing code execution accurately
  • Avoiding common pitfalls
View Unit 3 Study Guide

Ready for More Challenges?

Cycle 2 questions prepare you for the hardest AP CSA exam questions.

Study Games Practice FRQs
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.