![Learning Java by Building Android Games](https://wfqqreader-1252317822.image.myqcloud.com/cover/531/36699531/b_36699531.jpg)
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](https://epubservercos.yuewen.com/AF93C9/19470389601545806/epubprivate/OEBPS/Images/B09770_C03_02.jpg?sign=1738934502-NLKOHUyS2EAXEc6hRfjbNiSB9MaJFtag-0-5ef57acb40ccc5758f3e14d4ae213fcd)
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.