Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)
What is the correct way to return a boolean method in Java?

1 Answer

0 votes
by (13.1k points)

In Java, it is legal to have multiple returns like this:

if(somestatement)

{return true;

}

return false;

It is unnecessary to compare boolean values to true or false,

if(somestatement==true)

return true;

else if(somestatement==false)

return false;

here, somestatement==true and somestatement==false is completely unnecessary. You can simply write them like this:

if(somestatement)

return true;

else if(!somestatement)

return false;

Sometimes you cannot return the boolean value immediately, in that case you have to declare a variable and assign some boolean value like this:

boolean value=true;

if(somestatement)

{

//things to do here

value=false;

}

else if(!somestatement)

{

//things to do here

value=true;

}

return value;

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 9, 2021 in Java by Jake (7k points)
0 votes
1 answer

Browse Categories

...