How to stop the rest of code in current method from executing in Java?

I have 4 textboxes, 2 of them being password boxes (for the user to confirm their password).

Here’s my code:

public void actionPerformed(ActionEvent arg0) {
    String username = usernameField.getText();
    String emailAddress = emailField.getText();
    String password1 = passwordField1.getText();
    String password2 = passwordField2.getText();
    if (password1 != password2) {
        [code here]
    }
}

How can I make it so that if the passwords aren’t equal it stops the rest of the code in that method from executing?

Answer

There is a significant problem before you can do this: you have to compare strings correctly. Then, you can decide what to do if they’re false. Ultimately, using return in a void method is acceptable if you only want to return.

if (!password1.equals(password2)) {
    // [code here]
}

However, the better approach would be to do a simple blanket check, and avoid the early return – if the passwords are valid, then do operations in the scope of that block. The fall-through case would exit the method early.

public void actionPerformed(ActionEvent arg0) {
    String username = usernameField.getText();
    String emailAddress = emailField.getText();
    String password1 = passwordField1.getText();
    String password2 = passwordField2.getText();
    if (password1.equals(password2)) {
        // code on success here
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *