How to use variables

That's enough theory. Let's see how we would use our variables and types. Remember that each primitive type needs a specific amount of real device memory. This is one of the reasons that the compiler needs to know what type a variable will be. So, we must first declare a variable and its type before we try to do anything with it.

Declaring variables

To declare a variable of type int with the name score, we would type:

int score;

That's it. Simply state the type, in this case, int, then leave a space and type the name you want to use for the variable. Note also the semicolon ; on the end of the line will tell the compiler that we are done with this line and what follows, if anything, is not part of the declaration.

Similarly, for almost all the other variable types, the declaration would occur in the same way. Here are some examples. This process is like reserving a labeled storage box in the warehouse. The variable names used next are arbitrary.

long millisecondsElapsed;
float subHorizontalPosition;
boolean debugging;
String playerName;

So now we have reserved a space in the warehouse that is the Android device's memory, how do we put a value into that space?

Initializing variables

Initialization is the next step. Here, for each type, we initialize a value to the variable. Think about placing a value inside the storage box:

score = 1000;
millisecondsElapsed = 1438165116841l;// 29th July 2016 11:19 am
subHorizontalPosition = 129.52f;
debugging = true;
playerName = "David Braben";

Notice that the String uses a pair of double quotes "" to initialize a value.

We can also combine the declaration and initialization steps. In the following we declare and initialize the same variables as we have previously, but in one step:

int score = 1000;
long millisecondsElapsed = 1438165116841l;//29th July 2016 11:19am
float subHorizontalPosition = 129.52f;
boolean debugging = true;
String playerName = "David Braben";

Whether we declare and initialize separately or together is dependent upon the specific situation. The important thing is that we must do both at some point:

int a;
// That's me declared and ready to go?
// The line below tries to output a to the console
Log.d("debugging", "a = " + a);
// Oh no I forgot to initialize a!!

This would cause the following warning:

Initializing variables

There is a significant exception to this rule. Under certain circumstances, variables can have default values. We will see this in Chapter 8, Object-Oriented Programming; however, it is good practice to both declare and initialize variables.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.170.21