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:
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.