• No results found

Expressing yourself in Java

Let's try using some declarations, assignments and operators. When we bundle these elements together into some meaningful syntax, we call it an expression.

So let's write a quick app to try some out.

Here we will make a little side project so we can play with everything we have learned so far. We will need to create a new project, just as we did in the previous chapter but we will not need a UI this time.

Instead, we will simply write some Java code and examine its effects by outputting the values of variables to the Android console, called logcat. We will see exactly how this works by building the simple project and examining the code and the console output:

The following is a quick reminder of how to create a new project.

1. Close any currently open projects by navigating to File | Close Project. 2. Click on Start anew Android Studio project.

3. The Create New Project configuration window will appear. Fill in the

Application name field and Company Domain with packtpub.com or you could use your own company website name here instead.

4. Now click on the Next button. On the next screen, make sure the Phone and Tablet checkbox has a tick in it. Now we have to choose the earliest version of Android we want to build our app for. Go ahead and play with a few

options in the drop-down selector. You will see that the earlier the version

we select, the greater is the percentage of devices our app can support. However, the trade-off here is that the earlier the version we select fewer cutting-edge Android features will be available in our apps. A good balance is to select API 8: Android 2.2 (Froyo).

5. Click on Next. Now select Blank Activity and click on Next again.

6. On the next screen, simply change Activity Name to MainActivity and click on Finish.

7. As we did in Chapter 2, Getting Started with Android, to keep our code clear and simple, you can delete the two unneeded methods (onCreateOptionsMenu and onOptionsItemSelected) and their associated @override and @import statements. However, this is not necessary for the example to work.

For a detailed explanation and images of creating a new project, see Chapter 2, Getting Started with Android.

As with all the examples and projects in this book, you can copy or review the code

from the download bundle. You will find the code for this tutorial in the Chapter3/ ExpressionsInJava/MainActivity.java file. Just create the project as described previously and paste the code from MainActivity.java file from the download bundle to the MainActivity.java file that was generated when you created the project in Android Studio. Just ensure that the package name is the same as the one you chose when the project was created. However, I strongly recommend going along with the tutorial so that we can learn how to do everything for ourselves.

As this app uses the logcat console to show its output, you should run this app on the emulator only and not on a real Android device.

The app will not harm a real device, but you just won't be able to see

anything happening.

1. Create a new blank project called Expressions In Java.

2. Now, in the onCreate method just after the line where we use the setContentView method, add this code to declare and initialize some variables:

//first we declare and initialize a few variables int a = 10;

String b = "Alan Turing"; boolean c = true;

3. Now add the following code. This code simply outputs the value of our variables in a form where we can closely examine them in a minute:

//Let's look at how Android 'sees' these variables //by outputting them, one at a time to the console Log.i("info", "a = " + a);

Log.i("info", "b = " + b); Log.i("info", "c = " + c);

4. Now let's change our variables using the addition operator and another new

operator. See if you can work out the output values for variables a, b, and c before looking at the output and the code explanation:

//Now let's make some changes a++;

a = a + 10;

b = b + " was smarter than the average bear Booboo"; b = b + a;

c = (1 + 1 == 3);//1 + 1 is definitely 2! So false.

5. Let's output the values once more in the same way we did in step 3, but this

time, the output should be different:

//Now to output them all again Log.i("info", "a = " + a); Log.i("info", "b = " + b); Log.i("info", "c = " + c);

6. Run the program on an emulator in the usual way. You can see the output

by clicking on the Android tab from our "useful tabs" area below the Project Explorer.

Here is the output, with some of the unnecessary formatting stripped off: info﹕ a = 10

info﹕ b = Alan Turing info﹕ c = true

info﹕ a = 21

info﹕ b = Alan Turing was smarter than the average bear Booboo21 info﹕ c = false

Now let's discuss what happened. In step 2, we declared and initialized three variables:

• a: This is an int that holds the value 10

• b: This is a string that holds the name of an eminent computer scientist. • c: This is a Boolean that holds the value false

So when we output the values in step 3, it should be no surprise that we get the following:

info﹕ a = 10

info﹕ b = Alan Turing info﹕ c = true

In step 4, all the fun stuff happens. We add 1 to the value of our int a using the increment operator like this: a++;. Remember that a++ is the same as a = a + 1. We then add 10 to a. Note we are adding 10 to a after having already added 1. So we

get this output for a 10 + 1 + 10 operation:

info﹕ a = 21

Now let's examine our string, b. We appear to be using the addition operator on our eminent scientist. What is happening is what you could probably guess. We are adding together two strings "Alan Turing" and "was smarter than the average bear Booboo." When you add two strings together it is called concatenating and the + symbol doubles as the concatenation operator.

Finally, for our string, we appear to be adding int a to it. This is allowed and the value of a is concatenated to the end of b.

info﹕ b = Alan Turing was smarter than the average bear Booboo21

This does not work the other way round; you cannot add a string

to an int. This makes sense as there is no logical answer. a = a + b

Finally, let's look at the code that changes our Boolean, c, from true to false: c = (1+1=3);. Here, we are assigning to c the value of the expression contained within the brackets. This would be straightforward, but why the double equals (==)? We have jumped ahead of ourselves a little. The double equals sign is another operator called the comparison operator.

So we are really asking, does 1+1 equal 3? Clearly the answer is false. You might ask,

"why use == instead of =?" Simply to make it clear to the compiler when we mean to assign and when we mean to compare.

Inadvertently using = instead of == is a very common error.

The assignment operator (=) assigns the value on the right to the

value on the left, while the comparison operator (==) compares the

values on either side.

The compiler will warn us with an error when we do this but at

first glance you might swear the compiler is wrong. We will learn

more on this comparison operator and others later in the chapter and throughout the book.

Now let's use everything we know and a bit more to make our math game project.