Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

Trips through a loop

for (int i = 0; i < 8; i++) {
   System.out.println(i);
}
System.out.println("done");
image with no caption

Difference between for and while

A while loop has only the boolean test; it doesn’t have a built-in initialization or iteration expression. A while loop is good when you don’t know how many times to loop and just want to keep going while some condition is true. But if you know how many times to loop (e.g. the length of an array, 7 times, etc.), a for loop is cleaner. Here’s the loop above rewritten using while:

image with no caption

output:

image with no caption

++ --

Pre and Post Increment/Decrement Operator

The shortcut for adding or subtracting 1 from a variable.

x++;

is the same as:

x = x + 1;

They both mean the same thing in this context: “add 1 to the current value of x” or “increment x by 1” And:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial