• $10 Game Dev' Courses - Use code "BREAKTHRU"

    Video courses

The Complete Java Developer Course. Learn Step by Step

The Complete Android & Java Developer Course – Build 21 Apps

Master Android N App Development With Java

So what do loops have to do with programming? They are a way of repeating the same part of the code more than once. We can loop over code although potentially for a different outcome each time. This can simply mean doing the same thing until the code being looped over prompts the loop to end or it could be a predetermined number of times as specified by the loop code itself. We will look at all the types of loop that Java offers us that we will use when we build our first game. There are more that we will look at in the level two tutorials.

About this tutorial

Skill level 1
Time to read: 10 minutes

New Concepts:

  1. While loops
  2. Break
  3. For loops

While loops

Loops of the while variety are simple to understand. Think back to the if statements and their conditions. We could put the same combination of operators and variables in the conditional expression of the  while loop. With the while loop we also use an expression that can evaluate to true or false. Take a look at this code.

int x = 10;

while(x > 0){

	x--;
	// x decreases by one each pass through the loop

}

This is what is happening. Outside of the while loop int x is declared and initialized to 10. Then the while loop begins. Its condition is x > 0. So the while loop will continue looping through the code in its body until the condition evaluates to false. So the code above will execute 10 times.

On the first pass x equals 10 then 9 then 8 and so on. But once x is equal to 0 it is of course no longer greater than 0. Then the code will break out of the while loop and continue to run after the closing curly brace.

Just like a if statement, it is possible that the while loop will not execute even once. Take a look at this.

int x = 10;

while(x > 10){

	// more code here.
	// but it will never run unless x is greater than 10

}
  • Learning java by building Android games

    Learning Java by Building Android Games

    Want to learn Java for Android? Even if you are completely new to either Java, Android, or game programming but are aiming to publish Android games, then this book is for you. This book also acts as a refresher for those who already have experience in Java on other platforms or other object-oriented languages.
    • Setup your own Android game programming environment using Android Studio
    • Control logic, branch your code, and add real decision-making depth to your games
    • Design and use 2d sprite animations, smooth pixel graphics, sound FX, simple collision detection and artificial intelligence (AI)
    • Build around a dozen sample test apps and 4 complete working games!
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)
    small_book

    Android Game Programming by Example

    Learn to build exciting Android game projects. Build a simple flappy-bird like game to a multi-environment, tough, retro platformer then an OpenGL ES 2 Asteroids clone, running at hundreds of frames per second .
    • Animate your characters with sprite sheets, add multiple scrolling parallax backgrounds, and implement genuinely tough, playable levels in your games
    • Every single line of code is printed in the book! No need to refer to the code files while trying to follow along. All the code files are also supplied separately so you can refer to them in their completed form and copy/paste them into your project if you like.
    • Implement a multitude of other game features such as pickups, firing weapons, HUD’s, generating and playing sound FX, scenery, level transition, high scores, and more
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US Only)

Moreover, there is no limit to the complexity of the expression or the amount of code that can go in the loop body.

int playerLives = 3;
int alienShips = 10;

while(playerLives !=0 && alienShips !=0 ){

	//Entire game code here.
	//...
	//...
	//etc.

}

//continue here when either playerLives or alienShips = 0

The above while loop would continue to execute until either playerLives or alienShips was equal to zero. As soon as one of those conditions occurred the expression would evaluate to false and the program would continue to execute from the first line of code after the while loop.

It is worth noting that once the body of the loop has been entered it will always complete; even if the expression evaluates to a false part way through as it is not tested again until the code tries to start another pass. For example.

int x = 1;

while(x > 0){

	x--;
	// x is now 0 so the condition is false
	// But this line still runs
	// and this one
	// and me!

}

The above loop body will execute once. We can also set up a while loop that will run forever; unsurprisingly called an infinite loop. Here is one.

int x = 0;

while(true){

	x++; // I am going to get mighty big!

}

Breaking out of a loop

We might use an infinite loop like this so that we can decide when to exit the loop from within its body. We would do this by using the break keyword when we are ready to leave the loop body. Like this.

int x = 0;

while(true){

	x++; // I am going to get mighty big!

	break; // No you're not haha
	// Code doesn't reach here

}

And you might have been able to guess that we can combine any of the decision-making tools like if, else and switch with our while loops and all the rest of the loops, we will look at in a minute. For example.

int x = 0;
int tooBig = 10;

while(true){

	x++; //I am going to get mighty big!
	if(x == tooBig){
		break;
	} // No you're not haha.

	//code reaches here only until x = 10

}

It would be simple to go on for many more pages demonstrating the versatility of while loops but at some point, we want to start making games. So here is one last concept concerned with loops.

 Java for loops

Java for loops have a slightly more complicated syntax than while loops as they take three parts to set up. Have a look at the code first then we will break it apart.

for(int i = 0; i < 10; i ++){

	// Something that needs to happen 10 times goes here

}

Here is what all the parts of the condition do.

for(declaration and initialization; condition; change after each pass through loop)

To clarify further we have:
Declaration and initialization: We create a new int variable i and initialize it to .
Condition: Just like the other loops, it refers to the condition that must be true for the loop to continue.
Change after each pass through the loop: In the example i++ means that 1 is added/incremented to i on each pass.

for(int i = 10; i > 0; i--){

	// countdown

}

// blast off x = 0

The for loop essentially takes control of initialization, condition evaluation and the control variable on itself. We will see some neat ways we can use this in our games in a couple of tutorials time when we learn about arrays.

If you would like to practice what you have learnt in this tutorial try the mini-project Loops demo.

It is not hard to imagine that our code can quickly grow in length and complexity, even for a simple game. So let’s look at how we can organize our game code with methods.