How to check if a method returns true or false in an IF statement in Java?

Let's say I have a boolean method that uses an if statement to check if the return type should be true or false:

public boolean isValid() { boolean check; int number = 5; if (number > 4){ check = true; } else { check = false; } return check; 

And now I want to use this method as a parameter of an if statement in another :

 if(isValid == true) // <-- this is where I'm not sure //stop and go back to the beginning of the program else //continue on with the program 

So, basically, what I'm asking is, how can I check what the return type of the boolean method is in the parameters of the if statement? Your answers are deeply appreciated.

+7
source share
8 answers

Since this is a method to call it, you must use parens afterwards, so your code will look like this:

 if(isValid()) { // something } else { //something else } 
+9
source
 public boolean isValid() { int number = 5; return number > 4; } 

 if (isValid()) { ... } else { ... } 
+3
source

You should be able to simply call the function in the IF clause to:

 if (isValid()) { }else { } 

Since isValid() returns a boolean , the condition will be evaluated immediately. I heard that it is better to create a local var before you check the condition.

  boolean tempBoo = isValid(); if (tempBoo) { }else { } 
+2
source

- If operator accepts only a boolean value.

 public boolean isValid() { boolean check = false; // always intialize the local variable int number = 5; if (number > 4){ check = true; } else { check = false; } return check; } if(isValid()){ // Do something if its true }else{ // Do something if its false } 
+1
source

This is how you do it

 if(isValid()) { } else { } 
0
source
 if (isValid()) { // do something when the method returned true } else { // do something else when the method returned false } 
0
source

You can use:

 if(isValid()){ //do something.... } else { //do something.... } 
0
source
 public boolean isValid() { boolean check; int number = 5; if (number > 4){ check = true; } else { check = false; } return check; 

How can you do this whole method without boolean checking?

So how to get rid of .. check = true, check = false, return check stuff?

0
source

All Articles