RSS Feed

Returning A Simple If Else True Or False Statement Android Studio Java

This is covered on my web page

Very often you just want to return true or false from a function. Often it is a simple matter of checking an if statement. I think for readability, possible performance gains I think this is the best way.

Take this for example. I have a function called myFunction(int x). All I want to do is determine whether instring = “abc”. A silly example I know but I am illustrating an easy way of returning a value from a one line function.

public boolean myFunction(String inString)


if (inString == “abc”)  
             return true;

         } else
             return false;

Better written in my opinion like so..

public boolean myFunction(String inString) { return inString == “abc” ; }

This is a very silly example but you would be surprised how many people write the first bit of code in my example. And there are reasons why you may need this construct. I’ll have to leave you to understand when this might be required but at least you know how you might return a boolean from a simple if else statement..






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: