When we code a computer game, the first thing we need it to do is to ‘know’ what the current state of the game is. This might include the player’s score, how many enemy space ships there are, where on the screen all the game objects are and what they are doing. The game’s variables are the part of our code that allows us to do this.
[widgets_on_pages id=”udemy_advert_java_1″][widgets_on_pages id=”udemy_code_details”]

About this tutorial

Skill level 1
Time to read: 10 minutes

New Concepts:

  1. Java variables
  2. Declaration
  3. Initialization

Recommended preparation tutorials

Projects related to or that demonstrate these concepts

All of these things are part of the data of the game. And it is very easy to think of lots more examples of data, a typical game might need. What about the images for the graphics, what if each object has a different image for each of many frames of animation? What about data to describe the game environment, artificial intelligence or the layout of the different levels of a game? All this information, even in a simple retro 2d shooter, for example, will become fairly extensive once the whole game is considered.

Fortunately, the Java programming language solves this problem for us; with variables. Variables enable us to easily store data in a meaningful, accessible and flexible way. Let’s look at some simple examples to start with.

We mentioned a moment ago that we would need to remember the player’s score. To manage this particular piece of data we can create a variable in our code and we can make it meaningful by giving this variable an appropriate name. Let’s call our variable to hold the player’s score  playerScore.

Variable naming conventions

You might have noticed that the name is simply a combination of the two words, with the first letter of the first word in lowercase and the first letter of the second word in upper case. In Java, we can call our variables almost anything we want but by using meaningful names there is never any doubt about what the variable is for. In addition, by using the combination of lower and upper case letters we are adopting a naming convention. By sticking to a naming convention especially when our code eventually becomes more extensive, will make our code more readable and easy to follow.

Naming conventions vary from language to language, company to company and different preferences for particular conventions abound. In Java, you can choose your convention of choice -unless you’re being paid to follow a specific convention. Here we are using the simple lower case word followed by upper case word because it makes the second word clear and when we introduce more types of Java code later in the course it will make our variables stand out from other types of code.

Java variable types

The next thing we need to do, before we can begin to write code for our variables, Java forces us to decide what type of variable it will be. Types are simple to understand. It is just a case of thinking about what information (what type) any particular variable will be used to store. In the case of our playerScore variable, we are storing a number, a score. But let’s consider some other potential variable types.

What about the name of the player, perhaps we could use a variable called playerName. Here we don’t want to store a number but a collection of letters from the alphabet that form the player’s name. Think perhaps also about data that stores if something has occurred- or not, that is true or false. This is much more common than it might first seem and some examples soon will help. Also consider we might need to use different types of number, just like in the real world. Whole numbers, fractions etc.

To avoid any ambiguity about what type a variable is, Java makes us declare a type before we can use a variable. This makes it plain what that variable will be used to store. Java then knows how much space is required but also, because it can help us enforce rules about the correct usage of different types. As we progress with this Java course and complete our first projects we will see this is a very useful feature.

Let’s have a look at some common types in Java. The list below is a mere fraction of the full range of available types; all the variable types should appear fairly straight forward with the exception of one really powerful variable type, known simply as an object or class, which will be covered in the tutorial Understanding OOP for coding Java games. We can write almost any game with just these seven types.

Type Explanation
int For whole numbers, negative as well as positive.Numbers in the range of +- 2,147,483,647
String For storing any textual information. From a players name to a small book.
float For storing numbers with a floating point. Numbers with a decimal fraction (1.5 or 3.141 etc).
long For storing numbers with a value too large for int. Numbers up to +- 9,223,372,036,854,775,807.
boolean This is a special variable that can only be one of two values; true or false. This type of variable is perfect for making decisions about what to do next. Is the enemy shooting? Is the game over? And much more.
Array Arrays are denoted with the symbols []. And they are used for storing groups of any other type of variable. Perhaps a whole fleet of alien space ships. We will cover arrays in the tutorial Handling game data with Java arrays
Class object Class objects can be nearly anything at all. They are a special type of variable which not only stores values but also behavior. The player, a game character or even the game itself could be an object.

The table shows the seven key variable types that will allow us to make almost any game. The last one, Object, is the most powerful of all and will be covered at level 2.
[widgets_on_pages id=”udemy_advert_java_3″][widgets_on_pages id=”udemy_code_details”]

How variables work

We can think of a variable as a kind of storage space. And when we declare a variable along with its type Java not only reserves a space in memory, appropriate for that type but also links the name we give it to that space. So whenever we refer to playerScore we access whatever value is stored at a location in memory set aside for it. We don’t need to worry about how it works or where in our computer’s RAM it is. This leaves us free to work on the important aspects of our game without concerning ourselves about how computer memory is managed by whatever hardware our game is running on.

This happens in two steps; declaration followed by initialization. We have already mentioned we must declare our variables so let’s have a look at what that code might look like then we will look at the second step, initialization.

Declaring a variable

We can declare a variable in Java like this:

int playerScore;
String playerName;
float valuePi;
long millisecondsSince1970;
boolean isAlive;

Above we simply state the type followed by the variable name and end the line with a semicolon. We add the semicolon to the end of the line to tell the Java compiler that it is the end of the line.

On line 1 of our code we have a int type variable (for numbers) called playerScore and on line 2 a String type variable (for textual data) called playerName. Next, on line 3 we have a float type variable called valuePi which can hold a decimal fraction that could represent pi (3.141…). Then on line 4 we declare a variable of the type long to hold a number with what will be a quite large value, implied from the name, the number of milliseconds since the start of 1970. This is surprisingly useful as we will see when we make our first game.

Notice in the examples above and the examples that follow we have left out further discussion of arrays and objects for a later time.

Initializing a variable

Now we have declared the variables with meaningful names we can initialize those same variables with appropriate values, like this:

playerScore = 0;
playerName = "Alan Turing";
valuePi = 3.141f;
millisecondsSince1970 = 1415187526;
//the above is true this 5th November morning in 2014
isAlive = true;

Notice on the end of the float initialisation we append an f. This is required in Java to distinguish the number from other floating point types that Java can use. We could optionally combine the declaration and initialization into one step, like this:

Declaring and initializing in one step

int playerScore = 0;
String playerName = "Alan Turing";
float valuePi = 3.141f;
long millisecondsSince1970 = 1415187526;
boolean isAlive = true;

Remember that Java helps us enforce the rules about a variable’s type. So we couldn’t do this:

Types matter and cannot be used with the wrong type of data.

playerScore = "Alan Turing";
//error Strings are not the same as int
isAlive = 10;
//boolean can either be true or false

What next?

Of course, to make our variables any use at all we need to be able to read them and manipulate them. So let’s learn about changing the value of game variables with expressions. Or, if you haven’t already, you might like to consider setting up an Android development environment ready to do some projects.