Picture
Lesson #1-5: More on Variables:
We will be talking about variables in this lesson.
Refer to the phone pseudo-class that I created as an example:

Picture

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! Variables = Fields!)

First, recall that Classes are blueprints for creating objects. Every time you create an object with this class, you are instantiating (creating an instance, or copy, 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. (No need to write it yourself). 
It will (hopefully) clear some things up. 
Picture
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 (if ever) 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: 
Picture
(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 TAKES THE VALUE OF 2.3." It will make it easier to conceptualize).

Recall that we created a static double (decimal variables) 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). 
Picture
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 type of 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 correctly inform you that the variable doesn't exist!

Example: 
Picture
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: 
Picture
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... 
Picture
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? Read the last few paragraphs a few more times, and then comment below.
__________________

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. 

See you in Day 4!
 


Comments

Reece
11/13/2012 2:55pm

This is really helping me. Thank you!

Reply
Golczi
11/29/2012 1:49pm

wow, I've read several lessons from this site and they're great. Really helpful, thanks for sharing !

Reply
dazzlar
12/12/2012 10:27am

Both togglePower and pressPowerButton methods needs some review fyi.
Needs to be an else if statement there.

Reply
senseofnickels
01/23/2013 8:36pm

Those methods work fine as-is, just not typical formatting. Probably just wanted to keep it as simple and straight-forward as possible for the current position in the tutorial.

Reply
batsman
01/29/2013 8:56am

The parameters are a bit confusing to me

If i understand it right then it goes like this:

The main methods hello variables value is 2.0

And the secundary method takes the "hello" variable and gives adds 5 to its value making it 7.0

So if you would calculate the hello = hello + pi in the main method you would get 5.14

And in the secundary methos you would get 10.14

The secundary method is able to use the "hello" vaariable of the main method, but i dont understand why the main method invokes the secundary methods altered "hello" method

Reply
batsman
01/29/2013 8:59am

I mean the "hello" variable at the end, not hello method

Reply
batsman
01/29/2013 9:08am

I think i understand it now

If you want to use another methods variable you have to use the "methodname"(variable name) to call it
And then you are able to indicate witch methodd and variable you are refering to with thos statement

Then you can use the other methods variable in other methods, by indicating the variable in the same way

Reply
Aditya R link
03/02/2013 1:31am

What's a pseudo class?

Reply
Craig
04/27/2013 4:07pm

"Pseudo" means fake. It just means he is making up a fake class to explain the concepts. It's not something you would realistically use in an actual program.

Reply
engineer blogs link
05/13/2013 4:43am

Helpful info, i think it will help to be a programmer.

Reply
Antonio
05/20/2013 11:31am

This is so far the best tutorial i have ever seen. And is so good written that I understand perfectly and I am 15 years old and English is not my native language. Thank you a lot!

Reply
Abihshek link
06/19/2013 10:44am

so the secondaryMethod method with parameter hello prints 10.14 and when you used this method in main its value will be 10.14 so basically you are carrying 10.14 everywhere ( wherever you mention the secondary static method) ..

Reply
Dharmik Vadgama
07/08/2013 11:04am

Sir I want further clarification on what is an instance variable and what is a local one. I think it both are same.

Reply
AlexNovember
08/14/2013 1:34pm

I spent all night last night trying to understand Eclipse. It was 7:00 a.m. before I found this. Every other tutorial just throws the jargon at you, and this one explains it all bluntly. I applaud you, sir.

Reply
Toby Justus
09/05/2013 3:48am

I run the script and nothing happend. I added System.out.println(hello); and now i got the results only my first hello is 5.140000000000001 ???? any idea how this works?

Reply
Perceptic
09/06/2013 3:40pm

Doubles in java are represented as binary fractions so rounding sometimes occurs. If you want exact values you can use BigDecimal instead of a double. Google for more info.

Reply
dragonmaster61
09/07/2013 10:39am

I still don't understand most of it... But thanks for the explaination anyway.

Reply
david
10/06/2013 11:53am

i don't understand why the secondary method has the void modifier,

shouldn't type double be in place of void since it's returning a type double value when being invoked in the main method ?

any clarifications on this would be really appreciated thanks !

Reply



Leave a Reply

    Author

    James Cho is the lead developer at Kilobolt Studios. He is a college student at Duke University and loves soccer, music, and sharing knowledge.