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");
}
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:return startEngine
is always executed unconditionally and immediately terminates execution of the function. There's no way forif (engineNoise == 2)
to be executed.NB. It always pays off to properly format and indent your code and to use braces. Your first example
Is actually:
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.