[Android Software Development] tjdwowh:
Day 3

Lesson #1-5: More on Variables:

Refer to the phone pseudo-class that I created as an example:

The three fields (also called variables) that I've created are: an integer variable called weight, a boolean variable called turnedOn, and a String object called color.

Today, we will discuss these in detail.

There are four kinds of variables (also called fields. < REMEMBER THIS OR YOU WILL BE CONFUSED):

First, recall that Classes are blueprints for creating objects. Every time you create an object with this class, you are instantiating (creating an instance of) this class. In other words, if you were to use the Phone class to create Phone objects, every time you created a new Phone object, you would have a new instance of the Phone class.

With each of these instances, variables that are defined in the class are also created. So each of these Phone instances will now have the weight, turnedOn, and String fields. When you make adjustments to a specific phone by, for example, adding 1 to weight, IT WILL ONLY AFFECT THAT PHONE. The other phone's weights are not affected. This means that each of these Phone objects have their own sets of fields (variables) that are independent from each other.

This is because the variables (fields) are...

1. Instance variables. When a variable is declared without the keyword "static" (i.e. "int weight = 0" rather than "static int weight = 0"), you are creating instance variables, which have unique values for each instance that they belong to.

What if you wanted to be able to change the values of these variables (again, fields) and affect every single Phone object that you created?

Then you create what we call...

2. Class variables. Any time that you declare a variable with the keyword "static" ("static int weight = 0"), you are basically saying that there will only be a single copy of this variable even if there are multiple Phone objects.

Have a look at the following example. It will (hopefully) clear some things up.

[COLOR="Blue"]
class AndroidPhone{
[/COLOR]
[COLOR="SeaGreen"]
//Declare and Initialize Variables (REMEMBER // IS A COMMENT INDICATOR).
//Note: doubles are used for decimal values (int are used for whole numbers).[/COLOR]
[COLOR="Blue"]
static double versionNumber = 2.2;
boolean turnedOn = false;
final String color = "blue";

public static void main(String[] args) {

...[/COLOR]

Pretend that we live in a world where you can make real life changes happen with Java.

Let's say Samsung has created 10 Android Phones using the AndroidPhone class above.

The next day, 10 users purchase these phones. We will label them phoneOne, phoneTwo, phoneThree, and so on.

When Samsung releases an update, they would want all 10 of these devices to get the update together (I know this isn't a very realistic scenario, just pretend)!

So they would use Eclipse to say:

[COLOR="SeaGreen"]//This line and the following line are comments (//).
//This is a method that updates phones:[/COLOR]
[COLOR="blue"]
static void updatePhones() {
versionNumber = 2.3;
}[/COLOR]

(Note: If you take the equal sign too mathematically, it will confuse you. So, whenever you give a value to a variable, try and interpret it like this:

"versionNumber is NOW EQUAL TO 2.3." It will make it easier to conceptualize.)

Recall that we created a static double called versionNumber. This means that when you change the value of versionNumber once, it will affect every instance of the AndroidPhone class, meaning that all 10 AndroidPhones will receive the update immediately!

It makes sense to create a static variable for the versionNumber, but it does not make sense to create a static variable for the power! You don't want the user to be able to turn off other people's phones - you want each phone to have its own "turnedOn" boolean (True/False variables).

How, then, do you select which phone will turn on or off?

It's rather simple!

Remember that we labeled each of these phones (phoneOne, phoneTwo, etc).

[COLOR="SeaGreen"]//If you are confused by the == and =, you should scroll up and review!
//Ctrl + F and search for "double equal sign"
//ALWAYS Pay attention to which brace corresponds with which![/COLOR]

[COLOR="Blue"]static void pressPowerButton{[/COLOR]

[COLOR="Red"]if (phoneOne.turnedOn == false){
phoneOne.turnedOn = true;
}[/COLOR]

[COLOR="Orange"]if (phoneOne.turnedOn == true){
phoneOne.turnedOn = false;
}[/COLOR]

[COLOR="seaGreen"]//Remember with equal signs:
//Think: "NOW EQUALS"[/COLOR]
[COLOR="blue"]}[/COLOR]
...

Now the final variable, "final String color = "blue";"

String means text, and we are creating a color variable with the value of "blue" (quotes indicate literals. no quotes would give color the value of a variable called blue).

The color of these 10 AndroidPhones will never change (ignore spraypaint and cases). So, we just indicate that they are "final."

In case you forgot (or skipped) how we got into the discussion of static, non-static, and final variables, we were talking about the four types of variables in Java.

Moving on to the third variable!

We've been creating variables that belonged to the class as a whole. Now we will talk about...

3. Local Variables. If you create a variable within a method, it will only belong to that method. If you try to invoke that variable by name in other methods, Eclipse will happily and truthfully inform you that the variable doesn't exist!

Example:

[COLOR="Blue"]public class localVariables {[/COLOR]

[COLOR="seaGreen"]//This is a Class-wide variable:
//You can use it in any method.[/COLOR]
static double pi = 3.14;

[COLOR="Red"]	public static void main(String[] args) {[/COLOR]

[COLOR="seaGreen"] //This is a local variable
//called hello.[/COLOR]

double hello = 2.0;

[COLOR="seaGreen"] //This means hello
//is NOW EQUAL TO
//pi + hello;[/COLOR]

hello = pi + hello;

[COLOR="Red"]}[/COLOR]

[COLOR="DarkOrange"]	static void secondaryMethod(){[/COLOR]
double hello = 4.0;

hello = pi + hello;
[COLOR="DarkOrange"]}[/COLOR]

[COLOR="blue"]}

[/COLOR]

There are three variables (NOT TWO) in this class.

1. The class variable called pi.

2. The local variable called hello in the main method.

3. The local variable called hello in the secondaryMethod.

REMEMBER:

When you declare and initialize a variable in a method, that variable will only belong to that method!

Let us finish with the discussion of the final type of variable:

4. Parameters. It is possible to use a local variable in multiple methods. This is how:

[COLOR="Blue"]public class localVariables {[/COLOR]

//This is a Class-wide variable:
//You can use it in any method.
static double pi = 3.14;
[COLOR="Red"]	public static void main(String[] args) {[/COLOR]

[COLOR="seaGreen"] //This is a local variable
//called hello.[/COLOR]

double hello = 2.0;

[COLOR="seaGreen"] //This means hello
//is NOW EQUAL TO
//pi + hello;[/COLOR]

hello = pi + hello;

//invoke secondaryMethod()

secondaryMethod(hello);

[COLOR="Red"]}[/COLOR]

[COLOR="DarkOrange"]	static void secondaryMethod(double hello){[/COLOR]
hello = hello + 5;
[COLOR="DarkOrange"]}[/COLOR]

Whenever you invoke a method, you use the "methodName();" statement.

If this method requires a parameter, the code will not successfully run (it will give you errors for that method).

The secondaryMethod requires a "double (decimal number)" to proceed. So you must pass in a double when you invoke the method...

[COLOR="DarkOrange"]secondaryMethod(hello);[/COLOR]

What this does (when you invoke secondaryMethod from the main method):

It takes the hello double from the main method and "sends it over" to the secondaryMethod, which labels it as a LOCAL VARIABLE called hello. So there are TWO hello variables involved, just like before. NOT ONE.

What does this mean?

Main method's hello will have a value of 5.14.

Secondary method's hello will have a value of 10.14.

Confused? PM me.

__________________

Just to clear things up regarding methods and invocation.

In Java, the code will typically be read from top to bottom.

As the programmer, you are basically doing one of two things:

1. Setting up things to be invoked.

2. Invoking (calling) things.

When you create a new method, let's say it's named methodName, it will be ignored until you explicitly call it into action by writing:

methodName();

You can see an example of this if you compare the examples for Local Variables and Parameters. In the Local Variables example, I setup the secondaryMethod() but I never call it to happen. So nothing inside it actually gets

reached when you press Play. However in the Parameters example, I state: secondaryMethod(hello);. This calls the secondaryMethod that I have setup, so everything inside will be reached and ran.

The only exception is the main method, because it is IMPLICITLY called when you press Play in Eclipse.

You can create as many methods as you want. They are there for your benefit: to group and organize your statements, and to make these statements easily accessible without re-writing each line of code.