AP Notes, Outlines, Study Guides, Vocabulary, Practice Exams and more!

Java Lesson 5

Jul 24, 2009

Java Lesson 5 – Loops

A cool feature in many programming languages is the ability to repeat code over and over. A common use for loops can be found in games. Games have an infinite loop that updates the game with new information, clears the screen, then redraws the game components using new information.
There are three different types of loops in Java. These consist of the for loop, the while loop, and the do-while loop.

The For loop
The for loop is used to execute a block of code a set number of times. A practical example may be that the player wants to add 50 things to his inventory. Do you really want to have to write 50 lines of code to do that? You could write 50 lines of code in 4 lines.
for(int i = 0; i < 50; i++)
{
// code to add an item to inventory
}
The line that is probably confusing the fun nuggets out of you is the first line. Well, to start a for loop, you type the word ‘for’ followed by a set of parentheses. Inside the parentheses, you need three tidbits of information. You need to specify where you want the loop begin counting from. You will almost always want to begin from 0. We do this by declaring a temporary variable for this loop. This variable won’t be recognized outside the loop. We are creating an int and simultaneously set it to zero. The loop uses this variable as a counter or a stopwatch so to speak. Second, we tell the loop how far we would like to loop for using ‘i’. This is saying that we will continue counting until ‘I’ reaches 50 or higher. So as long as ‘I’ is less than 50, continue looping. Lastly, we specify the amount we want to increment our loop variable after each pass of the loop. ‘++’ is shorthand notation for “add one to this number.”
Notice how our three bits of information are separated by semi-colons. Think of semi-colons as the Java equivalent of periods at the end of sentences.
Loops will continue in the next lesson.

Need Help?

We hope your visit has been a productive one. If you're having any problems, or would like to give some feedback, we'd love to hear from you.

For general help, questions, and suggestions, try our dedicated support forums.

If you need to contact the Course-Notes.Org web experience team, please use our contact form.

Need Notes?

While we strive to provide the most comprehensive notes for as many high school textbooks as possible, there are certainly going to be some that we miss. Drop us a note and let us know which textbooks you need. Be sure to include which edition of the textbook you are using! If we see enough demand, we'll do whatever we can to get those notes up on the site for you!