w3resource

Creating a Java Account Class with Validated Parameterized Constructor

Java Constructor: Exercise-6 with Solution

Constructor with Validation
Write a Java program to create a class called Account with instance variables accountNumber and balance. Implement a parameterized constructor that initializes these variables with validation:

  • accountNumber should be non-null and non-empty.
  • balance should be non-negative.
  • Print an error message if the validation fails.

Sample Solution:

Java Code:

Account.java

// Define the Account class
public class Account {
    // Private instance variables
    private String accountNumber;
    private double balance;

    // Parameterized constructor with validation
    public Account(String accountNumber, double balance) {
        // Validate accountNumber
        if (accountNumber == null || accountNumber.isEmpty()) {
            // Print error message if accountNumber is null or empty
            System.err.println("Error: Account number cannot be null or empty.");
            return;
        }
        // Validate balance
        if (balance < 0) {
            // Print error message if balance is negative
            System.err.println("Error: Balance cannot be negative.");
            return;
        }
        // Initialize accountNumber with the provided parameter
        this.accountNumber = accountNumber;
        // Initialize balance with the provided parameter
        this.balance = balance;
    }

    // Main method to test the Account class
    public static void main(String[] args) {
        // Test with valid data
        Account account1 = new Account("12340009", 1000.00);
        System.out.println("Account 1 Number: " + account1.accountNumber);
        System.out.println("Account 1 Balance: " + account1.balance);

        // Test with invalid accountNumber
        Account account2 = new Account("", 400.00);

        // Test with invalid balance
        Account account3 = new Account("1230000873", -200.00);
    }
}

Output:

Account 1 Number: 12340009
Account 1 Balance: 1000.0
Error: Account number cannot be null or empty.
Error: Balance cannot be negative.

Explanation:

  • Define the Account class:
    • The Account class is defined with the keyword class.
  • Private instance variables:
    • The Account class has two private instance variables: accountNumber (a String) and balance (a double).
  • Parameterized constructor with validation:
    • The parameterized constructor Account(String accountNumber, double balance) is defined.
    • Inside the constructor:
      • Validate accountNumber: Check if accountNumber is null or empty. If it is, print an error message and return from the constructor.
      • Validate balance: Check if balance is negative. If it is, print an error message and return from the constructor.
      • Initialize this.accountNumber with the provided accountNumber parameter.
      • Initialize this.balance with the provided balance parameter.
  • Main method:
    • The main method is defined to test the Account class.
    • Valid data:An Account object (account1) is created with valid data. The values of the instance variables are printed to the console.
    • Invalid accountNumber: An Account object (account2) is created with an empty accountNumber. An error message is printed.
    • Invalid balance: An Account object (account3) is created with a negative balance. An error message is printed.

Note on Constructors:

In the above exercise, the constructors for the Account class work by:

  • Parameterized Constructor with Validation: Initializes the accountNumber and balance instance variables only if the provided values pass the validation checks. This ensures that the accountNumber is non-null and non-empty, and the balance is non-negative.
  • Encapsulation: By keeping the instance variables private and initializing them through constructors with validation, the class ensures controlled initialization, data integrity, and appropriate error handling, encapsulating the logic for setting values and enforcing constraints within the class itself.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java Constructor Previous: Creating a Java Rectangle Class with Parameterized and Copy Constructors.
Java Constructor Next: Creating a Java Car Class with Parameterized Constructor and Default Values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/constructor/java-constructor-exercise-6.php