Learning Java by Building Android Games

4.5 (8 reviews total)
By John Horton
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Why Java, Android, and Games?
About this book

Android is the fastest growing operating system (OS) with one of the largest installed bases of any mobile OS. Android uses one of the most popular programming languages, Java, as the primary language for building apps of all types. So, you should first obtain a solid grasp of the Java language and its foundation APIs to improve the chances of succeeding as an Android app developer.

This book will show you how to get your Android development environment set up and you will soon have your first working game. The difficulty level grows steadily with the introduction of key Java topics such as loops, methods, and OOP. You'll then use them in the development of games. You will learn how to build a math test game, a Simon-like memory game, a retro pong-style game, and for the grand finale, a Snake-style, retro arcade game with real Google Play leaderboards and achievements. The book has a hands-on approach and is packed with screenshots.

Publication date:
January 2015


Chapter 1. Why Java, Android, and Games?

Welcome to Learning Java by Building Android Games, which I hope is just the beginning of your exciting journey into designing and writing games. By the end of this book, we will have made four complete games: a math quiz with dynamically increasing difficulty, a memory game in the style of the classic Simon toy, a pong-style squash game, and a clone of the classic Snake game.

Besides these games, we will build more than a dozen working apps to practice and demonstrate individual concepts to aid our learning of Java, Android, and games. Our games and apps will feature sound FX, graphics, and animations. We will learn everything from using the standard Android User Interface (UI) designer to creating smooth animations by plotting individual pixels.

Although I will encourage you to work with me and implement the specific projects that are detailed step by step throughout the book, I fully expect that once you grasp the different concepts, you will want to use them in your own unique creations without delay. This is exactly what I hope you will be inspired to do.

The game projects themselves are not the objective of the book but the means to a much loftier goal. By the end of the book, you will be able to design and implement your own 2D Android games, to sell or just to give away, on Google Play.


There is a bit of ground work to cover first, but I promise it won't take long and it won't be complicated either. Anyone can learn to program.

However, there are so many differing opinions among experts, which breeds confusion among beginners concerning the best ways of learning to program. So it is a good idea to look at why learning Java, Android, and games is an ideal pathway for beginners. This will be the first thing we will discuss in this book.

Here is what we will learn in this chapter:

  • Is this book for me?

  • Why should I use games to learn to program?

  • Why should I learn Java and Android?

  • Setting up our development environment


Is this book for me?

If you have already decided that Java, Android, or games are what you want to learn, then the next question might be, "Is this specific book for me?".

There are plenty of Java books for beginners and books by much more accomplished authors and programmers than myself. I have read many of them and admire the authors. However, when these books drift away—which they all do—to topics such as Java-native interfaces, web browser applets, or server-side remote communication, I sometimes find myself questioning their immediate relevance to me.

At this point, at least subconsciously, my commitment would wane and the learning process would slow or stop.

If you just want to learn pure Java

If you just want to learn Java on its own, this book will be a solid start. Although the Android stuff might be considered overhead to your pure Java learning, this is much less than the multitude of potentially unnecessary topics that would be introduced in any other Java book. The only caveat with this book is that the necessary overhead is all at the beginning. But once this minimal overhead is cleared, we can focus quite intently on Java.

With regard to the amount of overhead:

  • It will take about six pages to set up our programming environment in this chapter

  • It will take Chapter 2, Getting Started with Android, to get familiar with the Android tools, create your first working project, and glimpse your first real Java code

  • From then on, it will be nearly pure Java and building games

You will soon see that the tiny amount of overhead is not excessive and is well worthwhile.

If Android is your focus

If it was Android itself that made you look at this book, then I am proud to say this is the first book that will teach you Android without assuming you have any prior Java or programming knowledge whatsoever.

Where this book will take you

By the end of this book, you will be able to easily take one of many paths including these:

  • Learning Java at a higher level for any platform

  • Intermediate level Android learning including pure game frameworks (which will be covered in more detail in Chapter 9, Making Your Game the Next Big Thing)

  • A higher level of games development

  • Much easier tackling of any modern object-oriented language for things such as iOS, Windows, or web development

So if you know you want to learn Android or Java, hopefully, I have gone some way to make you commit to the way this book will help you. But why games, Android, or Java at all?


Why build games to learn to program?

Fun, of course! But there are other reasons too. Successfully running any program we have written is immensely satisfying, even more so when it involves using some code that we previously didn't understand.

But making our own games, as you will soon realize, creates a feeling of pleasure that is not easy to describe—it has to be experienced. Then there are added bonuses of sharing our creations with friends on a phone or tablet or even sharing them publicly on the Google Play Store, and you might realize that once you start making games, you can't stop.

As we create more complex games steadily, you'll realize that all techniques and pieces of code can be rehashed to create other games, and you can then start planning your very own unique masterpieces. This is exhilarating to say the least.

And as with many subjects, the more we practice the better we get. So games are a perfect way to start learning to program Java. However, most beginners' books for Android games require a fairly high level of Java knowledge. But as we will see, it is perfectly possible to keep the practical examples as fun game projects and still start with the very basics of Java.

There is a slight trade-off in doing things this way. We will not always approach the working game examples in a "by-the-book" manner. This is to avoid the problem of doing cartwheels before mastering the forward roll.

The learning outcome priority will always be the Java programming concept, followed by understanding the Android environment and game design principles. Having said that, we will closely examine and practice plenty of Android and game programming fundamentals.

Of course, from what we have just discussed, you can probably surmise that it would have been possible to teach a bit more Java in the same number of pages if we hadn't been making games.

This is true, but then we lose all the benefits that come with using games as the subject matter. Making games really can be a joy, and when our brains are open and eager for information, we will learn much faster. The minimal overhead of learning this way is negated a hundred times over. If games don't interest you in the slightest, then there are plenty of Java beginners' guides out there that take the traditional approach. Just don't expect quite the same thrill as when you publish your first game with online leaderboards and achievements.


Why Android and Java?

A part of successful learning is the commitment by the student, not just to do the work, but in their belief that they are doing the right thing in the right way. So many technology-based courses and books don't get that commitment from the reader, not subconsciously anyway.

The problem is the students' belief that they might be, partly at least, wasting their time with something that is or will soon become outdated or perhaps is not quite right for them. This can be true to a large extent with programming. So why should you spend your finite time learning Java, on Android?

Android is the fastest evolving and growing OS ever

At one time, Android updates emerged almost every two months. Even now, they emerge about once in six months. By comparison, Windows takes years between versions and even iOS updates come only yearly and usually change relatively little between versions. Android is obviously evolving and improving at an unprecedented rate.


Look at the history of Android versions since Version 1 at http://www.cnet.com/news/history-of-android/.

The first humble version of Android was released in 2008, around the same time when consumers were already quite excited about the then much flashier iPhone. News stories were also reporting that developers were getting rich by selling apps in the iTunes app store.

But in the last full year before this book was written, Samsung alone shipped more Android units than Apple sold all iOS devices combined. I am not joining the war on whose devices are best. I enjoy aspects of both Android and Apple, but purely in terms of picking a platform to learn on, you are probably in the right place at the right time with Android.

Android developers have great prospects

Now you might have picked up this book just for the fun and satisfaction that comes with learning to program games. But if you decide to develop your learning further, you will find that the demand for Android programmers is enormous and therefore very lucrative too.


Some data suggests salaries in excess of 100,000 US dollars. For more information, go to http://www.indeed.com/salary?q1=Android+Developer&l1=United+States.

Android is open source

What open source means is that although Google develops all the flavors of Android that are used on the newest devices, once the code is released, anybody can do whatever they like with it. Google only exerts control for a limited amount of time.

In practice, most Android users have the pure Google OS or the modified versions turned out by big manufacturers such as Samsung and HTC, but there is nothing to stop anybody taking the OS and changing, adapting, or converting it into whatever they like. In short, Android could never be taken away from the programming community.

Java is here to stay

Okay, so we see Android isn't likely to disappear but could Java become redundant? And will your significant time investment be wasted? On Android, as with most platforms, you can use many languages and tools. Android, however, was designed from the ground up to facilitate Java development. All other languages and tools are not invalid but tend to serve a fairly specific purpose, rather than be a real alternative to Java. In fact, as far as games are concerned, many of the alternatives to a pure Java development environment are also Java-based and require a good level of skill in Java to use. For example, the popular LibGDX game development library, which allows you to simultaneously make games for Android, iOS, Windows, Linux, Mac and even the Web, still uses Java! We will talk more about this in Chapter 9, Making Your Game the Next Big Thing. The point is that Java and Android are tied together and will likely thrive together.

Java is not just for Android

Java has been around a lot longer than Android, since the beginning of the 1990s in fact. Although what Java has been used for has evolved and diversified over more than two decades, the originally implemented strengths of the language itself remain the same today.

Java was designed to be platform- or computer-independent. This is achieved by the use of a virtual machine (VM). This is a program written in another language that decodes the Java program that we write and interacts with the computer platform it is running on. So as long as there is a VM for the computer you want to run your Java program on, with a few caveats, your Java program will work. So if you learn Java, you are learning a language that is used everywhere from the smart fridge to the Web and most places in between.

It is true, however, that the VM on each platform can and usually does implement features to specifically suit the uses it is likely to be put to. A clear example of this would be mobile-device-specific features such as sensors, GPS, or the built-in camera on many Android devices. Using Java with Android, you can take photos, detect the air pressure, and work out exactly where in the world you are. Most fridge VMs probably will not do this. So you can't always just run a Java program designed for device x on device y, but the language and syntax is the same. Learning Java on Android prepares you in a large part for Java in any situation. So rest assured that Java isn't going away any time soon.

Java is fast and easy to use

There is a decades-long debate over which language is the best overall or which language is the best to learn programming. Critics of Java will likely say things about Java's speed. It is true that the Java memory management along with the VM interpretation process does have some speed cost. However, these things have benefits; they significantly improve our productivity and the way that the Android VM interacts with a device largely negates the minor speed penalty. And since Android 4.4, it does so completely with Android Run Time (ART), which installs apps written in Java as fully native applications. Now Java programmers can build games in a friendly, interpreted language and have them run as if they were written in a more challenging natively compiled language.

A summary of Java and Android

In a rapidly changing world, if you are worried about where to invest your precious learning time, it is hard to have more confidence. Here we have a language (Java) whose fundamentals have remained almost the same for nearly a quarter of a century, and a platform (Android) that is backed by the biggest names in hardware, software, and retail, and though it's admittedly hugely influenced, it's not actually owned by anyone.

I am not an evangelist of any technology over another although it is true that I love doing stuff on Android. But you can be sure in your mind that if you are considering the best path to begin learning programming, there is a very strong argument that Java and Android are the best choice.

If you want to learn Java for any of its numerous uses, then this is a very good place to start. If you want to develop for Android or get into Android development of any sort, then Java is the absolute fundamental way to start, and making games has the enormous benefits we have already discussed.

By the end of the book, you will be able to write Java code for almost any Java-supported platform. You will be able use almost everything you learn in this book, away from the Android environment.

If you are planning to pursue a career or business by making Android games or any Android apps, then this book is possibly the only place to start for beginners.

If you are completely new to Java and want the easiest possible path to mastering it—the fastest growing platform on the planet—then Learning Java by Building Android Games will probably be just right for you.

So hopefully you are assured that the path this book will take to learn Java is as easy, fun, and thorough as learning Java can be. Let's get set up so we can start building games.


Setting up our development environment

The first thing we need to do is prepare our PC to develop for Android using Java. Fortunately, this is made quite simple for us.


If you are learning on Mac or Linux, everything in this book will still work. The next two tutorials have Windows-specific instructions and screenshots. However, it shouldn't be too difficult to vary the steps slightly to suit Mac or Linux.

All we need to do is:

  1. Install a software package called the Java Development Kit (JDK), which allows us to develop in Java.

  2. Install Android Studio, a program designed to make Android development fast and easy. Android Studio uses the JDK and some other Android-specific tools that automatically get installed when we install Android Studio.

Installing the JDK

The first thing we need to do is get the latest version of the JDK. To complete this guide, perform the following steps:

  1. You need to be on the Java website, so visit http://www.oracle.com/technetwork/java/javase/downloads/index.html.

  2. Find the three buttons shown in the following screenshot and click on the one that says JDK (highlighted). They are on the right-hand side of the web page. Click on the DOWNLOAD button under the JDK option:

  3. You will be taken to a page that has multiple options to download the JDK. In the Product/File description column, you need to click on the option that matches your operating system. Windows, Mac, Linux and some other less common options are all listed.

  4. A common question here is, "do I have 32- or 64-bit windows?". To find out, right-click on your My Computer (This PC on Windows 8) icon, click on the Properties option, and look under the System heading in the System type entry, as shown in the following screenshot:

  5. Click on the somewhat hidden Accept License Agreement checkbox:

  6. Now click on the download option for your OS and system type as previously determined. Wait for the download to finish.

  7. In your Downloads folder, double-click on the file you just downloaded. The latest version at time of writing this for a 64-bit Windows PC was jdk-8u5-windows-x64. If you are using Mac/Linux or have a 32-bit OS, your filename will vary accordingly.

  8. In the first of several install dialogs, click on the Next button and you will see the next dialog box:

  9. Accept the defaults shown in the previous screenshot by clicking on Next. In the next dialog box, you can accept the default install location by clicking on Next.

  10. Next is the last dialog of the Java installer. Click on Close.

    The JDK is now installed. Next we will make sure that Android Studio is able to use the JDK.

  11. Right-click on your My Computer (This PC on Windows 8) icon and navigate to Properties | Advanced system settings | Environment variables | New (under System variables, not under User variables). Now you can see the New System Variable dialog, as shown in the following screenshot:

  12. Type JAVA_HOME for Variable name and enter C:\Program Files\Java\jdk1.8.0_05 for the Variable value field. If you installed the JDK somewhere else, then the file path you enter in the Variable value: field will need to point to wherever you put it. Your exact file path will likely have a different ending to match the latest version of Java at the time you downloaded it.

  13. Click on OK to save your new settings. Now click on OK again to clear the Advanced system settings dialog.

Now we have the JDK installed on our PC. We are about half way towards starting to learn Java programming, but we need a friendly way to interact with the JDK and to help us make Android games in Java.

Android Studio

We learned that Android Studio is a tool that simplifies Android development and uses the JDK to allow us to write and build Java programs. There are other tools you can use instead of Android Studio. There are pros and cons in them all. For example, another extremely popular option is Eclipse. And as with so many things in programming, a strong argument can be made as to why you should use Eclipse instead of Android Studio. I use both, but what I hope you will love about Android Studio are the following elements:

  • It is a very neat and, despite still being under development, a very refined and clean interface.

  • It is much easier to get started compared to Eclipse because several Android tools that would otherwise need to be installed separately are already included in the package.

  • Android Studio is being developed by Google, based on another product called IntelliJ IDEA. There is a chance it will be the standard way to develop Android in the not-too-distant future.


If you want to use Eclipse, that's fine; all of the code in this book will work. However, some the keyboard shortcuts and user interface buttons will obviously be different. If you do not have Eclipse installed already and have no prior experience with Eclipse, then I even more strongly recommend you to go ahead with Android Studio.

Installing Android Studio

So without any delay, let's get Android Studio installed and then we can begin our first game project. To do this, let's visit https://developer.android.com/sdk/installing/studio.html.

  1. Click on the button labeled Download Android Studio to start the Android studio download. This will take you to another web page with a very similar-looking button to the one you just clicked on.

  2. Accept the license by checking in the checkbox, commence the download by clicking on the button labeled Download Android Studio for Windows, and wait for the download to complete. The exact text on the button will probably vary depending on the current latest version.

  3. In the folder in which you just downloaded Android Studio, right-click on the android-studio-bundle-135.12465-windows.exe file and click on Run as administrator. The end of your filename will vary depending upon the version of Android Studio and your operating system.

  4. When asked if you want to Allow the following program from an unknown publisher to make changes to your computer, click on Yes. On the next screen, click on Next.

  5. On the screen shown in the following screenshot, you can choose which users of your PC can use Android Studio. Choose whatever is right for you as all options will work, and then click on Next:

  6. In the next dialog, leave the default settings and then click on Next.

  7. Then on the Choose start menu folder dialog box, leave the defaults and click on Install.

  8. On the Installation complete dialog, click on Finish to run Android Studio for the first time.

  9. The next dialog is for users who have already used Android Studio, so assuming you are a first time user, select the I do not have a previous version of Android Studio or I do not want to import my settings checkbox, and then click on OK:

That was the last piece of software we needed. The simple nine-step process we just went through has actually set up a whole range of Android tools that we will begin to use in the next chapter.



We discussed why games, Java, and Android are not only extremely exciting but also arguably the best way to learn to program. This is because games can be an extremely motivating subject matter and Java and Android have enormous strengths with regards to popularity and longevity, and are open to all of us to use for free.

We also set up the Java development kit and installed Android Studio, getting ready for the next chapter where we will actually create a part of a working game and take our first look at some Java code.

About the Author
Latest Reviews (8 reviews total)
Very good book! However please do not insist in long answers, because sometimes it is hard to say more than a few words :)
Great PDF, excellent topics and delivery of explanation.
I have not started on this project but happy with the contents and the layout of the book.
Learning Java by Building Android Games
Unlock this book and the full library FREE for 7 days
Start now