Justin G
Justin G

Reputation: 182

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?

Upvotes: 0

Views: 119

Answers (4)

user3437460
user3437460

Reputation: 17454

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

I would say there are 2 ways:

  1. Let the program flow naturally to the end of the method:

    public void actionPerformed(ActionEvent e){
        if(password1.equals(password2)){
            //Do all the things if password is correct
        }            
    } //<-- If password is incorrect, point of execution will come to here 
    
  2. To exit a method before you reach the end of the method, you can use return:

    public void actionPerformed(ActionEvent e){
        if(!password1.equals(password2)){
            return;
        }
        else{
            //Do all the things if password is correct
        }
    }
    

Upvotes: 2

Makoto
Makoto

Reputation: 106440

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
    }
}

Upvotes: 3

Jake H.
Jake H.

Reputation: 969

You can add the return statement:

return;

Upvotes: 1

Maciej Cygan
Maciej Cygan

Reputation: 5471

Never compare strings with boolean operators - Bad practice!

To solve your question just do this:

if (!password1.equals(password2)) {
    return; 
}

Upvotes: 2

Related Questions