23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

It follows that the return statement must be the last statement executed <strong>in</strong> a<br />

function, as the rest of the code will never be reached.<br />

Note that there is a significant difference between a statement be<strong>in</strong>g the last l<strong>in</strong>e<br />

of code that is executed <strong>in</strong> a method <strong>and</strong> the last l<strong>in</strong>e of code <strong>in</strong> the method itself.<br />

In the example above, the l<strong>in</strong>e return true; is clearly not the last l<strong>in</strong>e of code<br />

that is written <strong>in</strong> the function, but it may be the last l<strong>in</strong>e that is executed (if the<br />

condition <strong>in</strong>volv<strong>in</strong>g date is true). Such a statement explicitly <strong>in</strong>terrupts the flow<br />

of control <strong>in</strong> the method. There are two other such explicit control-flow<br />

statements, which are used <strong>in</strong> conjunction with loops <strong>and</strong> switch statements.<br />

The break Statement<br />

The typical use of a break statement has the follow<strong>in</strong>g simple syntax:<br />

break;<br />

It is used to "break" out of the <strong>in</strong>nermost switch, for, while, or dowhile<br />

statement body. When it is executed, a break statement causes the flow of<br />

control to jump to the next l<strong>in</strong>e after the loop or switch to the body conta<strong>in</strong><strong>in</strong>g<br />

the break.<br />

The break statement can also be used <strong>in</strong> a labeled form to jump out of an<br />

outernested loop or switch statement. In this case, it has the syntax<br />

break label;<br />

where label is a <strong>Java</strong> identifier that is used to label a loop or switch statement.<br />

Such a label can only appear at the beg<strong>in</strong>n<strong>in</strong>g of the declaration of a loop. There<br />

are no other k<strong>in</strong>ds of "go to" statements <strong>in</strong> <strong>Java</strong>.<br />

We illustrate the use of a label with a break statement <strong>in</strong> the follow<strong>in</strong>g simple<br />

example:<br />

public static boolean hasZeroEntry (<strong>in</strong>t[][] a) {<br />

boolean foundFlag = false;<br />

zeroSearch:<br />

for (<strong>in</strong>t i=0; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!