13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

3.2 Fundamental Language Elements69• The expressi<strong>on</strong> that gets executed at the end of each loop iterati<strong>on</strong>, justprior to retesting the c<strong>on</strong>diti<strong>on</strong>alExample 3.11 A Java for loopfor (i = 0; i < 8; i++) {System.out.println(i);}Unlike C/C++, Java doesn’t have the comma operator for use within arbitraryexpressi<strong>on</strong>s, but the comma is supported as special syntax in Java forloops. It makes it possible to have multiple initializers in the opening of thefor loop and multiple expressi<strong>on</strong>s in the porti<strong>on</strong> repeated at each iterati<strong>on</strong> ofthe loop. The result is much the same—you can initialize and incrementmultiple variables or objects in your for loop.More formally, the full syntax of the for loop can be described with followingmeta-language as shown in Example 3.12 (where the []* means “zeroor more repetiti<strong>on</strong>s of”).Example 3.12 Java for loop syntaxfor ( before [, before]* ; exit_c<strong>on</strong>diti<strong>on</strong> ; each_time [, each_time]* )statementThe biggest difference between C and Java for loops, however, is that Javaallows you to declare <strong>on</strong>e or more variables of a single type in the initializingexpressi<strong>on</strong> of the for loop (Example 3.13). Such a variable’s scope is the forloop itself, so d<strong>on</strong>’t declare a variable there if you want to reference it outsidethe loop. It is a very handy c<strong>on</strong>struct, however, for enumerators, iterators, andsimple counters.Example 3.13 A Java for loop with local indexfor (int i = 0; i < 8; i++) {System.out.println(i);}

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

Saved successfully!

Ooh no, something went wrong!