Kilobolt
  • Home
  • Tutorials
    • Game Development Tutorial >
      • Unit 1: Beginning Java >
        • Before you begin...
        • Day 1: Setting Up
        • Day 2: Java Basics
        • Day 3: More Basics
        • Day 4: Java Math
        • Day 5: More Math
        • Day 6: If... else...
        • Day 7: More Control Flow
        • Day 8: Looping
        • Day 9: More on Looping
        • Day 10: Inheritance, Interface
        • Day 11: Threads and Graphics
      • Unit 2: Creating a Game I >
        • Day 1: Foundations
        • Day 2: Basic Framework
        • Day 3: Taking User Input
        • Day 4: Enter the Robot
        • Day 5: Background and Sprites
        • Day 6: Adding Enemies
        • Day 7: Shooting Bullets
        • Day 8: Animations
        • Day 9: 2D-Arrays
        • Day 10: Painting the Tilemap
      • Unit 3: Creating a Game II >
        • Day 1: Level Creation - Part 1
        • Day 2: Level Creation - Part 2
        • Day 3: Level Creation - Part 3
        • Collision Detection Basics
        • Day 4: Collision Detection Part 1
        • Day 5: Collision Detection Part 2
        • Day 6: Collision Detection Part 3
        • Day 7: Health System & Death
        • Day 8: Basic AI & Final Touches
      • Unit 4: Android Game Development >
        • Day 1: Introduction to Android
        • Day 2: Setting up for Development
        • Day 3: Creating our First Android Application
        • Day 4: Parts of an Android Application
        • Day 5: The Android Game Framework: Part I
        • Day 6: The Android Game Framework: Part II
        • Create an Android Game From Scratch (or port your existing game)
        • Day 7: Creating an Android Game (From Start to Finish)
      • Reference Sheet
    • Zombie Bird Tutorial (Flappy Bird Remake) >
      • Unit 1: Building the Game >
        • Introduction
        • Day 1: Flappy Bird - An In-depth Analysis
        • Day 2: Setting up libGDX
        • Day 3: Understanding the libGDX Framework
        • Day 4: GameWorld and GameRenderer and the Orthographic Camera
        • Day 5: The Flight of the Dead - Adding the Bird
        • Day 6: Adding Graphics - Welcome to the Necropolis
        • Day 7: The Grass, the Bird and the Skull Pipe
        • Day 8: Collision Detection and Sound Effects
        • Day 9: Finishing Gameplay and Basic UI
        • Day 10: GameStates and High Score
        • Day 11: Supporting iOS/Android + SplashScreen, Menus and Tweening
        • Day 12: Completed UI & Source Code
    • Android Application Development Tutorial >
      • Unit 1: Writing Basic Android Apps >
        • Before you begin...
        • Day 1: Android 101
        • Day 2: Getting to Know the Android Project
        • Day 3: The Development Machine
        • Day 4: Building a Music App - Part 1: Building Blocks
        • Day 5: Building a Music App - Part 2: Intents
        • Day 6: Building a Music App - Part 3: Activity Lifecycles
  • New Forum
  • About Us
    • Contact Us
  • Our Games
    • TUMBL: FallDown
  • Facebook
  • Twitter

GAME DEVELOPMENT TUTORIAL: DAY 1-3: More Basics

9/16/2012

55 Comments

 
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 of the Object 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 (and go away when that method is finished). 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!
Day 2: Java Basics
Go to Day 4: Java Math
55 Comments
Reece
11/13/2012 06:55:05 am

This is really helping me. Thank you!

Reply
Golczi
11/29/2012 05:49:53 am

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

Reply
dazzlar
12/12/2012 02:27:49 am

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

Reply
Science
6/23/2014 07:55:52 am

Seconded.

Reply
Noah
8/19/2014 02:03:28 am

The way he has written it is not "wrong", it might be more readable with an if else. In those two cases the variable in question will only be one of two options: true or false. So only one of those if conditions will be done.

Reply
cosin
1/11/2015 08:42:04 pm

No it is not ok. If you pass turnedon = true it will not change(toggle), it will first enter first if and become false, then it will enter second if statement and change to true again.

So if you want a toggling behaviour second if should be changed with "else if".

senseofnickels
1/23/2013 12:36:58 pm

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
1/29/2013 12:56:38 am

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
1/29/2013 12:59:35 am

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

Reply
batsman
1/29/2013 01:08:00 am

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
3/1/2013 05:31:12 pm

What's a pseudo class?

Reply
Craig
4/27/2013 09:07:39 am

"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
5/12/2013 09:43:16 pm

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

Reply
Antonio
5/20/2013 04:31:52 am

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
6/19/2013 03:44:03 am

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
7/8/2013 04:04:20 am

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

Reply
Noah
8/19/2014 02:13:48 am

Using the authors definitions...
Instance variables are the same as class variables (if you're comfortable with c++), meaning they will exist with every instance of the class.

class Foo{
Foo() {}
int bar =0; //instance variable
}

So if I use class Foo like so...

Foo one = new Foo();
Foo two = new Foo();

Each instance of Foo has a variable "bar" that is completely independent of each other.

one.bar = 6; //doesn't change two.bar

Local variables are variable that are local to a method or function. So if I add a method like so.

class Foo{
... //previous code
public methodOne(){
int a = 9; //this variable only exists in methodOne
}
}

There is no way to get to "a" inside methodOne. It is created when the method is invoked and is destroyed when the method finishes.

Hope this helps.

Reply
AlexNovember
8/14/2013 06:34:01 am

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
9/4/2013 08:48:34 pm

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
9/6/2013 08:40:21 am

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
9/7/2013 03:39:41 am

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

Reply
david
10/6/2013 04:53:33 am

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
Noah
8/19/2014 02:17:48 am

The void on the secondary method means that it will not return anything!

Look at the method again, there is no return statement.

If you added a

return(hello);

then you would need to change the void to a double.

Reply
muneer
12/16/2013 01:09:29 pm

you invoked the secondarymethod(hellow) in main method and it take the value 5.14. but my doubt is that without invoking the secondarymethod(hellow) .is hellow will take the value 5.14?

Reply
Axe55
1/9/2014 12:56:03 am

First thnkx alot for this tutorial.

Can't understand this :
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

static double versionNumber = 2.2

static "double" <== please explain double here

Reply
Noah
8/19/2014 02:21:29 am

That double is just describing the type of data you want to "put in" the cubby hole labeled "versionNumber"

The static means that you can make as many instances of a class like...

AndroidPhone ph1 = new AndroidPhone();
AndroidPhone ph2 = new AndroidPhone();
AndroidPhone ph3 = new AndroidPhone();
AndroidPhone ph4 = new AndroidPhone();
AndroidPhone ph5 = new AndroidPhone();

and every one of these....

ph1.versionNumber
...
ph5.versionNumber

would equal 2.2

master
1/22/2014 08:58:13 pm

I don't get what the variables mean. please help!!!

Reply
Gilad V Pinker
1/24/2014 07:25:32 am

Think Variables as an apartments.

Your computer is a huge block of apartments.

You have the choice to declare apartments that you can sell, and you have the choice to choose what kind of apartments(Big flat, condo,penthouse apartment etc.)

Now, you have the choice to choose what kind of people would you want in there and you can use them later (as workers, maintenance etc.)


I know that's not a very good example (although it'll help you understanding what objects are), I'll explain you varbs in the right way:

Variable is a pointer, wich points on a specific place in your computers memory.
Variables are used to store values in your memory.
You can choose what kind of memory you want to store, for example: a number, a character( 'a','b','c'), a string of characters or even a true or false statement.

You'll use variable ALOT while programming. :)

if this isn't clear enough, I'll try to explain it again, or just try to read this lecture again and don't forget to read the next lectures either.


Thank you for reading,
Uncle.V

Reply
Gilad V Pinker
1/24/2014 07:25:59 am

Think Variables as an apartments.
Your computer is a huge block of apartments.
You have the choice to declare apartments that you can sell, and you have the choice to choose what kind of apartments(Big flat, condo,penthouse apartment etc.)
Now, you have the choice to choose what kind of people would you want in there and you can use them later (as workers, maintenance etc.)
I know that's not a very good example (although it'll help you understanding what objects are), I'll explain you varbs in the right way:
Variable is a pointer, wich points on a specific place in your computers memory.
Variables are used to store values in your memory.
You can choose what kind of memory you want to store, for example: a number, a character( 'a','b','c'), a string of characters or even a true or false statement.
You'll use variable ALOT while programming. :)
if this isn't clear enough, I'll try to explain it again, or just try to read this lecture again and don't forget to read the next lectures either.
Thank you for reading,
Uncle.V

Reply
Gilad V Pinker
1/24/2014 07:26:48 am

Think of variables as an apartments.Your computer is a huge block of apartments.You have the choice to declare apartments that you can sell, and you have the choice to choose what kind of apartments(Big flat, condo,penthouse apartment etc.)Now, you have the choice to choose what kind of people would you want in there and you can use them later (as workers, maintenance etc.)
I know that's not a very good example (although it'll help you understanding what objects are), I'll explain you varbs in the right way:
Variable is a pointer, wich points on a specific place in your computers memory.Variables are used to store values in your memory.You can choose what kind of memory you want to store, for example: a number, a character( 'a','b','c'), a string of characters or even a true or false statement.You'll use variable ALOT while programming. :)
if this isn't clear enough, I'll try to explain it again, or just try to read this lecture again and don't forget to read the next lectures either.
Thank you for reading,
Uncle.V

Reply
Gilad V Pinker
1/24/2014 07:26:59 am

test

Reply
Gilad Pinker
1/24/2014 07:27:13 am

Think of variables as an apartments.Your computer is a huge block of apartments.You have the choice to declare apartments that you can sell, and you have the choice to choose what kind of apartments(Big flat, condo,penthouse apartment etc.)Now, you have the choice to choose what kind of people would you want in there and you can use them later (as workers, maintenance etc.)
I know that's not a very good example (although it'll help you understanding what objects are), I'll explain you varbs in the right way:
Variable is a pointer, wich points on a specific place in your computers memory.Variables are used to store values in your memory.You can choose what kind of memory you want to store, for example: a number, a character( 'a','b','c'), a string of characters or even a true or false statement.You'll use variable ALOT while programming. :)
if this isn't clear enough, I'll try to explain it again, or just try to read this lecture again and don't forget to read the next lectures either.
Thank you for reading,
Uncle.V

Reply
Gilad Vlad Pinker
1/24/2014 07:15:22 am

I have already programmed in Java (never enough), and I started this course.
Just to make sure I don't miss anything (and even strengthening my basic knowledge) I'm reading those lectures.

It'll be really! really! helpful if the website programmers would add some "skip-points" where I could know when does a new topic starts or ends :)

Reply
shane bailey
2/11/2014 11:36:35 am

To be honest I think I have to go back to day 1! (note to self) :~( don't try and learn when have just finished work and extremely tired.

Reply
GraveUypo
2/13/2014 04:12:51 am

Wow these are very well made. In fact, they explain things way more clearly and to-the-point than my stupid teachers ever managed to in college. For god's sake, i left there without clearly knowing what static void meant, and in the first 5 minutes of reading this (i skipped the first couple of pages almost entirely) i have a crystal-clear understanding of them. I wonder why they never managed to teach something so simple.

Anyways, I haven't messed with java in a great while and i needed a refresher course. This is by far the best thing i've found so far in the internet. I'm gonna read it all before jumping in the mobile game dev tutorials.

Reply
jeem
2/14/2014 02:50:57 pm

Do I always need to write the main method in a class.

Reply
jeem
2/14/2014 03:14:24 pm

In C++ we generally use the main method outside of a class.But here I have seen that the main method is used inside of a class.So while working with multiple class do I need to write the main in different class.If I declared a class private does that mean I can not create its object in other class?

Reply
Jesse Galvas
3/25/2014 08:03:00 pm

so I was playing around with this, trying to get it to display all the values, and I came out with something a bit strange, first, here's my code


public class HelloWorld {
static double pi = 3.14;

public static void main(String[] args) {
double hello = 2.0;
double hi = pi + hello;
secondaryMethod(hi);
System.out.println(pi);
System.out.println(hello);
System.out.println(hi);
}

static void secondaryMethod(double hi) {
hi = hi + 5;
System.out.println(hi);
// Method Body
}
}


now here are my results

10.14
3.14
2.0
5.140000000000001

my question is this: the last System.out.println command caused the 10.14, so why does 10.14 appear first in my console?

Reply
Atekihcan
4/22/2014 03:01:08 pm

Because System.out.println(hi) inside secondaryMethod() is not the last print command.

The flow of the code is as follows...
# main() calls secondaryMethod()
# secondaryMethod() prints the value of local variable hi, which at this point has the value 10.14
# Now main() prints the values of pi, hello, and hi

Reply
Raichu
8/1/2014 09:19:15 am

In the 6th screenshot you fergot to make the // comment green.
Nice tutorial!

Reply
Vincent.C link
8/6/2014 12:31:33 pm

What does literal means and what it does? When to apply?

string color = "blue"
string color = blue

thanks in advance.

Reply
Noah
8/19/2014 02:28:15 am

What he means is it "literally" means what you put between the quotes.

So....
string color = "blue"; //color now holds the value "blue"

string color = red; /*the compiler will look for a variable of type string (or something it knows how to convert into a string) named red if it does not find one you will get an error*/

In the second case if all works and you do have a string called red then color will hold what ever sting red was set to.

Reply
Noah
8/19/2014 02:29:37 am

Great Job on the tutorial so far!
Excited to keep reading. I hope I am being helpful. I do have a BS in Computer Science.

Reply
Alonso
9/28/2014 07:22:55 pm

when i try to run it doesn't run, it says that the selection cannot Launch, and there are no recent launches.

Reply
Jimmy Dev link
10/9/2014 06:53:55 pm

I am still confushed aboout (string [] args) what is this? why is it used?

Reply
ahamed
10/18/2014 08:39:50 pm

ME too.. I coudnt understand that,, And I want to know what is public,main,args,void and static ?? plz tell me

Reply
Slavomir
12/26/2014 07:41:51 pm

Perfect tutorial. But it is not very good explained inthis lesson how to change static variable. How can somebody call the function for changing static variable? Inside class or after making an instance ? ....

Reply
Mick link
3/11/2015 08:51:39 am

At of date...

Reply
Astemac
4/12/2015 10:15:25 pm

Thanks James Cho.....
Your tutorials are very easy to understand and helpful (& too they are free!!!)
They help me to learn java basics
Once again Thanks a lot!!!

Reply
el
8/4/2015 11:57:12 am

I understand that static double pie is a class wide variable and can be used in any method but I fail to understand the final conclusion. the main method had a local variable called Hello with a value of 2.0 it then call the class wide variable making it pi+hello which is equal to 5.14 . then the secondary method is invocked which takes the variable "hello" and adds 5 to it. WHERE DID THE "5" COME FROM. am I the only one going crazy trying to figure out where this random value came from. any help would be much appreciated thank you.
P.S great tutorial thanks

Reply
Rossana
2/15/2016 09:38:33 pm

Thanks for the tutorial, it's kind of easy to understand to a real beginner. Great Job, please keep it up.
However, I cannot make sense to the boolean turnedOn = false;
if (turnedOn == true) {turnedOn = false;}
if (turnedOn == false) {turnedOn = true;}

Please try to explain its meaning and function, thanks.

Reply
Raven
5/17/2016 12:09:30 am

Hi Rossana,

He made some logical error here.
Actually it should be

if (turnedOn == true) {turnedOn = false;}
else if (turnedOn == false) {turnedOn = true;}

it means that when you press the power button of your phone, the press power button method gets called

hence if(phone is ON){
phone gets OFF
}
else if(phone is OFF){
phone gets ON
}

Reply
kareem
3/11/2016 12:46:14 am

man i stay cant understand anything should i start the course from the day 1 again

Reply
Rossana
3/13/2016 06:35:28 pm

Hi Kareem,
It helps if you download the eclipse as suggested and try the code along side the tutorial. Though I can't claim of understanding it all, it helps to realise some logic. Re- read the tutorial also helps as well. Good Luck! Rossana

Reply
Raven
5/17/2016 12:04:03 am

Why static void pressPowerButton method doesn't have brackets after the method's name?
Shouldn't it be static void pressPowerButton() ?

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. 


© 2014 Kilobolt, LLC. All rights reserved.