I need help on how to return a boolean method in java. This is the sample code:
public boolean verifyPwd(){         if (!(pword.equals(pwdRetypePwd.getText()))){                   txtaError.setEditable(true);                   txtaError.setText("*Password didn't match!");                   txtaError.setForeground(Color.red);                   txtaError.setEditable(false);            }         else {             addNewUser();         }         return //what? }   I want the verifyPwd() to return a value on either true or false whenever I want to call that method. I want to call that method like this:
if (verifyPwd()==true){     //do task } else {     //do task }   How to set the value for that method?
Java Boolean equals() method The equals() method of Java Boolean class returns a Boolean value. It returns true if the argument is not null and is a Boolean object that represents the same Boolean value as this object, else it returns false.
A Boolean expression is a Java expression that returns a Boolean value: true or false .
Answer: Boolean is a primitive data type in Java that has two return values. A boolean variable can return either “true” or “false”.
Just add a return false; outside the for loop so that the method has a return statement in all possible conditions. This means that even if the method execution never finds a match, even then the method should be able to return a boolean value, i.e. false which means it didn't find any match.
You're allowed to have more than one return statement, so it's legal to write
if (some_condition) {   return true; } return false;   It's also unnecessary to compare boolean values to true or false, so you can write
if (verifyPwd())  {   // do_task }   Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.
boolean success = true;  if (some_condition) {   // Handle the condition.   success = false; } else if (some_other_condition) {   // Handle the other condition.   success = false; } if (another_condition) {   // Handle the third condition. }  // Do some more critical things.  return success; 
                        try this:
public boolean verifyPwd(){         if (!(pword.equals(pwdRetypePwd.getText()))){                   txtaError.setEditable(true);                   txtaError.setText("*Password didn't match!");                   txtaError.setForeground(Color.red);                   txtaError.setEditable(false);                   return false;            }         else {             return true;         }          }  if (verifyPwd()==true){     addNewUser(); } else {     // passwords do not match  System.out.println("password do not match"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With