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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Str<strong>in</strong>g s = " " + 4.5; // correct, but<br />

poor style<br />

Str<strong>in</strong>g t = "Value = " + 13;<br />

Str<strong>in</strong>g u = Integer.toStr<strong>in</strong>g(22);<br />

good<br />

// this is good<br />

// this is<br />

1.4 Control Flow<br />

Control flow <strong>in</strong> <strong>Java</strong> is similar to that of other high-level languages. We review the<br />

basic structure <strong>and</strong> syntax of control flow <strong>in</strong> <strong>Java</strong> <strong>in</strong> this section, <strong>in</strong>clud<strong>in</strong>g method<br />

returns, if statements, switch statements, loops, <strong>and</strong> restricted forms of "jumps"<br />

(the break <strong>and</strong> cont<strong>in</strong>ue statements).<br />

1.4.1 The If <strong>and</strong> Switch Statements<br />

In <strong>Java</strong>, conditionals work similarly to the way they work <strong>in</strong> other languages. They<br />

provide a way to make a decision <strong>and</strong> then execute one or more different statement<br />

blocks based on the outcome of that decision.<br />

The If Statement<br />

The syntax of a simple if statement is as follows:<br />

if (boolean_exp)<br />

else<br />

true_statement<br />

false_statement<br />

where boolean_exp is a Boolean expression <strong>and</strong> true_statement <strong>and</strong><br />

false_statement are each either a s<strong>in</strong>gle statment or a block of statements enclosed<br />

<strong>in</strong> braces ("{" <strong>and</strong> "}"). Note that, unlike some similar languages, the value tested<br />

by an if statement <strong>in</strong> <strong>Java</strong> must be a Boolean expression. In particular, it is<br />

def<strong>in</strong>itely not an <strong>in</strong>teger expression. Nevertheless, as <strong>in</strong> other similar languages,<br />

the else part (<strong>and</strong> its associated statement) <strong>in</strong> a <strong>Java</strong> if statement is optional.<br />

There is also a way to group a number of Boolean tests, as follows:<br />

if (first_boolean_exp)<br />

true_statement<br />

51

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

Saved successfully!

Ooh no, something went wrong!