Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Javaa:Tutorial - The Loop


  • Please log in to reply
No replies to this topic

#1 John


    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 09 December 2006 - 08:01 AM

As with all programming languages I know, there are two types of loops. The while loop and the for loop which, in all practicality, do the same exact thing; execute code while a condition is true. When I first started programming, I always preferred the while loop because I could never memorize the syntax of the for loop. However, now that I have memorized the proper syntax it is usually the only type of loop I use, because it is more concise, which is a very good programming tactic to follow. If you can write a piece of code in three lines rather than five, it is easier to reed.

The basic structure of a loop is as follows:

while(true) {
//evaluate the code

A loop that actually does something might look like this.

int x = 0;
while(x < 5){

Java also as a do…while loop. The main difference between the while loop and the do…while loop is that the do…while loop always runs at least once. For example take a look at the code below

 int x = 0;
do {
} while (x >= 5);

The variable x is never greater than or equal to five, but it still prints the initial value of x, 0. However, although looking at the while loops, each line should make perfect sence, there are two lines of unnecessary code, and while we strive to be “good” programmers, we frown upon that; which is why there is a for loop. The for loop looks like this

for(int x = 0; x < 5, x++){

  • 0

Also tagged with one or more of these keywords: loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download