Why is an Unreachable code error in this sequence of code and not the latter?

47 Views Asked by At
public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2)
        System.out.println("This car needs a service");
    return startEngine;
    
        
    }

But this sequence causes an Unreachable code error. Why is the location of the If statement causing the method to fail?

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    
    return startEngine;
    
    if (engineNoise==2)
        System.out.println("This car needs a service");
        
    }
    
        
1

There are 1 best solutions below

1
On

Because in the first example, if you take all possible paths through the method, all statements will be executed.

However, in your second example, the if statement can never be executed:

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    
    return startEngine; // <-- EXECUTED UNCONDITIONALLY, FUNCTION TERMINATES
    
    if (engineNoise==2)
        System.out.println("This car needs a service");        
}

return startEngine is always executed unconditionally and immediately terminates execution of the function. There's no way for if (engineNoise == 2) to be executed.

NB. It always pays off to properly format and indent your code and to use braces. Your first example

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2)
        System.out.println("This car needs a service");
    return startEngine;
}

Is actually:

public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2) {
        System.out.println("This car needs a service");
    }
    return startEngine;
}

so it is not only the order of lines, but the nesting of your code blocks that affects execution. Anything inside the body of an if-statement is only executed conditionally.