Search code examples
javaif-statementcurly-braces

Curly braces in if-else blocks


I'm programming in java and I happened to find myself with this:

if(nodo == null) return null;
    else if(nodo.izquierda!=null && nodo.derecha==null)
        return nodo.izquierda;
    else if(nodo.izquierda==null && nodo.derecha!=null)
        return nodo.derecha;
    else return null; // si ambos hijos son nulos o no nulos

My question is: Is it the same to write that as:

if(nodo == null) 
    return null;
else {
    if(nodo.izquierda!=null && nodo.derecha==null)
        return nodo.izquierda;
    else {
        if(nodo.izquierda==null && nodo.derecha!=null)
              return nodo.derecha;
        else return null; // si ambos hijos son nulos o no nulos
    }
 }

More than anything I'm confused by how to use the curly braces with if-else blocks. Is it necesary to use curly braces?

For example:

if (something)
     if (something else)
     ...
     else (blah blah)

Is the same that:

if (something)
{
     if (something else)
     ...
     else (blah blah)
}

Solution

  • For example:

    if (something)
          if (something else)
          ...
          else (blah blah)
    

    Is the same that:

     if (something)
       {
          if (something else)
          ...
          else (blah blah)
       }
    

    In this case, yes, they're the same, but the former is harder to read than the latter. I recommend using braces always, even for blocks of code made of a single line.