0

Why isn't this structure acceptable? Anyway it returns a boolean value right??

public boolean a()
{

    if(condition)
    {
        if(condition)
        {
            if(condition)
            {
                return true;
            }
        }
    }

} 
2
  • if all controll flows results in a value being returned it is acceptable Commented Aug 3, 2013 at 8:16
  • 1
    @ Dixon : You should understand that if one of the if conditions are not satisfied, it will not return anything. Commented Aug 3, 2013 at 8:22

4 Answers 4

4

It's not valid because there is a possibilty where nothing is returned. Your method is declared as returning a boolean value, so it MUST return a boolean value at some point in the code before the method is finished, regardless of the inner logic. If your if-statement if (condition) is false, the method doesn't have another return statement, so the code won't even compile. To fix this, add a "default" return value:

public boolean a()
{
    if(condition)
    {
        if(condition)
        {
            if(condition)
            {
                return true;
            }
        }
    }
    return false;
} 
Sign up to request clarification or add additional context in comments.

Comments

3

Not valid because you need to do a return some default value (return) .

What if conditions not satisfied ??

valid is :

public boolean a()
    {

        if(condition)
        {
            if(condition)
            {
                if(condition)
                {
                    return true;
                }
            }
        }
    return false;

    } 

As a side note,To make your code mode readable,I suggest

  if(condition && condition && condition) 
        {
         return true;
        }
  return false;

Prefer to read jls-14.17

Comments

0

Though the method returns true when the condition is satisfied, it doesn't specify a return value when the condition isn't satisfied. The method should cover all the code paths (read conditional statements).

Comments

0

As the answers above correctly state, you absolutely have to return something in Java. C doesn't really care.

In order to avoid this I would recommend decreasing the level of nesting to do something like

boolean value=false; //default return
if(cond && cond)
    return value;
if(cond)
    return false; //if you want to be more specific
if(cond)
    value=true;

return value;

so a value gets returned no matter what. On the plus side, readability increases

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.