Snowman
Snowman

Reputation: 32061

Syntax of a return statement in Java

This is in one of my practice exams.

return search(p,key,0,p.length-1) !=null;

How would this look with if statements?

Upvotes: 0

Views: 2451

Answers (3)

pstanton
pstanton

Reputation: 36640

the only other answer, which is arguably more legible and better if you need to step through the code to debug would be to assign the result of the method to a variable:

Object result = search(p, key, 0, p.length - 1);
return result != null;

... with 'if statement':

Object result = search(p, key, 0, p.length - 1);

if (result == null)
    return false;
else
    return true;

... with 'if statements' (not recommended):

Object result = search(p, key, 0, p.length - 1);

if (result == null)
    return false;

if (result != null)
    return true;

Upvotes: 2

shinkou
shinkou

Reputation: 5154

For school assignments, I'd suggest you do something like

...
public boolean func(String p, String key)
{
    boolean bOut = false;

    ...

    if (search(p, key, 0, p.length - 1) != null)
        bOut = true;

    return bOut;
}
...

Otherwise, Amir's answer would just work perfectly.

Upvotes: 1

Amir Afghani
Amir Afghani

Reputation: 38531

if (search(p,key,0,p.length-1) !=null) { 

   return true;

}

return false;

Upvotes: 2

Related Questions