Even more JAVA programming basics...

This document was written by CS 290W TA Joshua Kay and was last modified

Okay, we're back for more basic programming skills. We finished the for statement, so let's check out another cool way to do loops. It's called, appropriately enough, while(). Let's check out some code, okay?
int x=0; while (x<10) { g.drawString("x = "+x,25,25+15*x); x++; } First of all, we have the statement int x=0; - This is not part of the while loop, but rather just pointing out that all variables need to be initialized somewhere.

while(x<10); - This simply states that while x is less than ten, perform the actions inside the squiggly brackets. Note that there is *NO* semicolon between the arguments for the while() and the beginning of the squiggly brackets.

Inside of the brackets, it looks a lot like the for statements. Except for one thing - the x gets increased INSIDE of the brackets, and not inside the while statement itself. This isn't a huge difference most of the time, but sometimes very necessary, and it can also make your programs much easier to write, depending on what it is you need to do.

Finally, note that there is *NO* semicolon after the squiggly brackets - just like the for statement.

Let's try another cool loop style - this is called do...while - Ex:

int x=0; do { g.drawString("x = "+x,25,25+15*x); x=x+1; } while (x<10); Now what could be useful about yet another style of loop? Well, sometimes, you want to do something at least once, even if the condition isn't met. You see, the program hits the do, and instantly begins performing the action inside of the squiggly brackets. It will draw on the Applet, just the same as the for and while loops, and then it will check to see whether the condition is met.

Too, notice here something is different. The while statement has a semicolon *AFTER* it. This is necessary JAVA syntax.

Why would you need this? Well consider washing your car, with soap. You have to rinse it *once*, right? Even if you don't think you can see the soap? Then, you check to see if you need to rinse again. Then you check again, and again, until your car is rinsed.

Look at the following:

int x=0; do { g.drawString("x = "+x,25,25+15*x); x=x+1; } while(x>10); Well, x is equal to zero, but the condition says while x>10, correct? So does the action inside of the squiggly brackets still get performed?

The answer is YES. do...while statements *ALWAYS* perform the action the first time, before the condition is ever checked.