If you have two if statements for:
int n = -1;
if (n < 0)
return null;
if (n <= 1)
return "yay";
Will it return null or yay? Will it run through the code top to bottom and stop at the first if statement, or will the last one be used?
The first
ifstatement will be evaluated first, of course.nwhich is-1is in fact< 0, so the body of code associated with thatifstatement will be executed.nullwill be returned.What might be confusing you is that, though the second
ifstatement would evaluate true, it will never be evaluated. This is because areturnstatement, when executed, leaves the function/method it is inside of.If you wrote:
xwould be set to0.xwould be returned. Any lines of code after the return would never execute.Here’s another example, to clarify:
xwould be set to10.xwhich is10is in fact not< 0, so theifstatement’s body will be skipped.xwould be set to0.