• 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)>
      • 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
  • Forum
  • About Us
    • Contact Us
  • Our Games
    • TUMBL: FallDown
  • Donate
  • Facebook
  • Twitter

GAME DEVELOPMENT TUTORIAL: DAY 1-2: Java Basics

09/16/2012

44 Comments

 
Picture
Welcome to Day 2 of Kilobolt's Android game development tutorial series.


Lesson #1-3: Examining Java:

Today, we will dissect a Java class. For some of you, this will be your very first encounter with raw code.
But first... let's talk about Eclipse.

Yesterday, we left off at the welcome screen. You won't ever need to see it again. Just exit out of the tab like so:
Picture
Now you will be greeted with the screen you will see every time you open Eclipse: the workbench. Don't worry too much about the different panels. You will learn what each of them do eventually. For now, just check the following things.

1. Eclipse has multiple perspectives suited for different tasks. Check to see that the currently selected perspective is Java. If it is not Java, go to Window > Open Perspective > Other and select Java. 
Picture
Picture
2. Look at the bottom panel. If you see a Console tab, move on. 
If not, go to Window > Show View > Console. This will display the Console tab, where our program will display text and error messages to us.
Picture
You are now ready to start programming! 

Take a look at the Package Explorer - it's on the left side of the screen. This is where Eclipse will organize all of your projects. If you are ready to start coding, read on!

1. Press File > New > Java Project.
2. Enter a project name of your choice. I will use "KiloboltTutorialSeries." 

Creating a Java Project creates a folder that will hold all the files (code and other assets) that your program needs.
Picture
3. Press Finish. You should now see the project in your package explorer.
4. Double click on it to expand it. You will see the following: 
Picture
__________________________________________________
src is where all of your Java source code will be created.

JRE System Library (if your version of Java is not JavaSE - 1.7 like my screenshot, don't worry about it. We won't have compatibility issues) contains pre-written Java code -- the massive Java library (the "built-in" code) -- that you can import into your own projects. This is there so programmers like me and you do not have to waste time writing code to perform frequently performed operations; you can just import it.

Sometime in your programming career, you will hear the phrases "high level" and "low level" programming. "High level" typically refers to the type of code that the developer interacts with on a regular basis. It is the simplest and most intuitive form of the language. "Low level" functions, on the other hand, are lines of code that directly translate into computer action. 

We will, for the most part, be dealing with high-level programming, while some of the code in the JRE will deal with lower level programming.
__________________________________________________

5. RIGHT-CLICK on src, select New, and create a (Java) Class file. Name it HelloWorld. 
(By convention, class names start capitalized, and every subsequent word is capitalized!)
Picture
6. Hopefully you will see this screen! 
Picture
Let's talk quickly about Java syntax, or grammar. 

1. The purple words "public class" basically are descriptors of the word HelloWorld that follows. They are declaring that HelloWorld is a class that is public (it can be accessed by other classes). 

2. The curly braces define where the class begins and ends. The opening { denotes the beginning of the class and the closing } denotes the end of the class. Your entire class is within these two braces.

In Java, the curly braces are used to tell the compiler (which converts our Java code into code that computers can understand) where a certain section of your code begins and ends.

So what exactly is a class? 
First, let us talk about objects.

Objects, in the real world, describe things that have both a state and behavior. For example, your phone's state can be: turned on or turned off while its behavior can be: displaying a game or playing music.

Objects, in programming, are similar. They too have a state and behavior, storing state in fields, also called variables, and behaving via use of methods. 

A class, then, is the "blueprint from which individual objects are created" -- a template. Classes are used to create objects, and classes also define these objects' states and behaviors.

The class we have created together, HelloWorld, is not the best example for what a class is, so here's another example class that better illustrates one: 
Picture
Let's dissect this class. Pay careful attention to the braces, which have been color coded to demonstrate where each brace's counterpart is. (Notice how the indents give us a sense of hierarchy. The red braces comprise the largest section of the class, the brown braces comprise the second largest section, which in turn comprises two identically sized yellow and green sections).

The red braces contain the class called Phone. In other words, it contains the blueprint that you use to create Phone objects. This class contains one method called togglePower, which as we have mentioned before is used to express or change the behavior of an object - it is a way of doing something.

The yellow braces denote the beginning and end of the method called togglePower. This method checks the value of the boolean variable "turnedOn" and acts accordingly.

The green braces denote the beginning and end of one conditional if statement, and the blue braces do the same for another conditional if statement.

If you have never programmed before, I know some of these things must be strange to you, so let me explain some of these oddities.

1. Whenever a line begins with //, everything that follows is considered a "comment," meaning that the computer will ignore it. You can use comments to leave a note for yourself (for future reference) or for other programmers (to be able to easily discern the purpose of the following lines of code).

2. After the first comment, notice the three "statements" (sentences in our language):  
  1. int weight = 0;
  2. boolean turnedOn = false;
  3. String color = "blue";
All three of these are variables. You may have learned in math that variables are letters or symbols that represent another numerical value. 

In programming, a variable can be an integer (negative whole numbers, zero, and positive whole numbers), a boolean (true or false), or String (text), among several others. We will talk about these types later.

As before, the purple text modifies the following word. If we refer to the first statement:
int weight = 0;

This statement is creating an integer variable called "weight" and assigning a value of 0 (using the equal sign - this is called initializing a variable, giving it an initial value).

Refering to the second statement:
boolean turnedOn = false;

This statement is creating a boolean variable called "turnedOn" (by convention, Java variables begin lower case and capitalize every subsequent word, like "firstSecondThirdFourth") and assigning a value of "false."

I'm sure you get the idea and can explain the third statement.


You probably have noticed that each of these statements end with a ;

Well, think of the semicolon as the period (.) in Java. It is another punctuation that will prevent your statements from becoming "run-on statements." As a general rule, whenever you are making a declarative statement, you would use a semicolon. More on this later.


Now one last thing:

There is an equal sign = and there is a double equal sign ==.

The first of these, the assignment operator, assigns the Second item as the value of the First item (i.e. "weight = 0" assigns 0 as the value of weight).

The latter of these is comparitive. It compares the first item with the second item (i.e. "turnedOn == true" DOESN'T assign true as the value of "turnedOn" but rather checks if "turnedOn" IS EQUAL to true).

An alternative explanation can be found here: http://www.javacoffeebreak.com/faq/faq0022.html
_________________

Lesson #1-3.5: A Quick Lesson on Naming:

In Java, you can name classes or variables whatever you want as long as it is not one of those purple words that Java has reserved for its own use (public, static, void, int, etc).

Classes are typically named like so:

ExampleClassName.

Methods and variables are named like so:

exampleMethodName()

and 

exampleVariableName.

This is called camel casing.

In the Phone class above, togglePower is just a made-up name. 
So until you fill that togglePower method with statements (instrutions), togglePower is just a blank method.

_________________

Lesson #1-4: Writing our first program:

You should have a class called HelloWorld now as shown below:

  1. public class HelloWorld {
  2.  
  3. }
We are now going to add a method called the main method to this class. If you do not remember what a method does, scroll up and do a quick review before proceeding.

A main method (the method by the name of main) is the "entry-point" for your program. It will automatically be invoked (or called) when you run the program - in other words, pressing the Run (Play) button will run the main method. Nothing more.

Dissecting the Main Method: 
  1. public static void main(String[] args) {
  2.    // Method body
  3. }

1. public, static, void - are Java modifiers. 
We will discuss these in detail later, but know that these three words are what we would call Java keywords, meaning that these words are already pre-defined in Java and you cannot use them as variable names or method names (you can use them as part of the full name, however). The three words here describe what type of method main is, the answer to which is, public, static, and void.

public - visible to other classes. Java programs usually incorporate multiple class files, so if you want to refer to code in the class from other classes, you make it public. (The opposite is private).

static - means that this method belongs to the Class, not an instance of the class. Recall that classes are blueprints for creating objects. The main method is the first piece of code that runs. Since we have no way of creating the HelloWorld object to call its main method, it has to be static. If that doesn't make sense, don't worry too much about it. We will discuss it in detail later.

void - whenever we call a method (call means to ask for it to run), we can ask to receive a value back. Void means that no value will be returned. For example, if we have a method that adds two values together, then we would not write void, but int, so that the method can return an int value representing the sum.

If none of these things make sense to you, that is okay! You will begin to understand as we write some more code.

 2. Methods, in Java, are indicated like below:

I. methodOne() 

This above method is called "methodOne" and requires no arguments, or parameters, for the method to work.

II. methodTwo(type argumentName)

This above method is called "methodTwo" and requires an argument of the declared type (which can be int, boolean, etc). 

When dealing with a method that requires an argument, at the moment it is invoked (or called by using a statement), it will ask for an input. It will take this input and use it in the method. I will show you how this works in the following examples.

3. Applying #2 to the main method:

main(String[] args)

We know that the main method requires an argument of type String called args. The [] indicates that this is an array, which you can think of as a table of corresponding x and y values. For now, just know that this is what goes in as the argument of the main method every time. You do not need to understand why or what it means just yet. Trust me.


Here is the main method with its braces: 
  1. public class HelloWorld {
  2.  
  3.    public static void main(String[] args) {
  4.       // Method Body
  5.    }
  6.  
  7. }
If you were to copy this code into eclipse and pressed Run, it would compile successfully and run. 

The problem is... the main method is empty. It won't do anything yet.

So let's write our first statement (or command): 
  1. System.out.println("Hello Kilobolt!");
Pretty basic right? No? Let's dissect it.

1. System refers to a class in the library that I've mentioned before (from which you can import code), also known as the API (Application Programming Interface). 

2. The periods between "System" and "out" & "out" and "println" represent hierarchy. This is called the dot operator. When we use a "." on an object, we are able to refer to one of its variables or methods.

For example: 

HelloWorld.main(args);

would invoke the main method in the class HelloWorld (not that you would ever do that since main methods are called automatically).

3. println requires an argument. Inside it, you can type both literals (meaning things that represent themselves) and variables (things that contain values).

You indicate literals with quotes: " " and variable names can just be written.
I will show you an example on this.

(Note: If you want to know more about the System.out.println and how it works at the lowest level, you can refer to this site: http://luckytoilet.wordpress.com/201...-really-works/
But I recommend not doing so until you have a better understanding of Java).

I know it's frustrating for some of you to be writing code that you don't yet fully understand, but just bear with me for a while. Everything will become clear.

Now we insert the statement into the Main Method to get the full working code: 
  1. public class HelloWorld {
  2.    
  3.     public static void main(String[] args) {
  4.         System.out.println("Hello Kilobolt!");
  5.     }
  6.  
  7. }
Copy and paste this into eclipse and press Run! 
You should see: 
 Hello Kilobolt! 
What's going on here? When you press Run, the main method is called. The main method has one statement (System.out...)
which displays "Hello Kilobolt!"

NOTE: To make it easier to tell which brace goes corresponds with which, press Ctrl + Shift + F. This auto-formats your code! 


This concludes Day 2.
See you in Day 3, and like us on Facebook!
Go to Day 1: Setting Up
Go to Day 3: More Basics
 


Comments

nax
10/31/2012 7:05am

hi kilobolt
first thank you for your amazing tutorial
but i have some problem
why when i type "public class HelloWorld" the color isn't blue like yours?
and "public static . . .." isn't green like yours?
sorry i'm new to this and just start learning thanks again

Reply
James C.
10/31/2012 7:42am

I color coded it so it's easy to see which curly brace { } goes with which:

https://kilobolt.com/uploads/1/2/5/7/12571940/1691606_orig.png

Don't worry if it looks different :)

Reply
Reece
11/13/2012 2:08pm

This is really helpful! thank you very much, I'm hoping you'll have the 3D stuff up by the time I work all the way through to it.

Reply
Sam
11/15/2012 8:35am

When I try to run this it comes up with this error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method printIn(String) is undefined for the type PrintStream

at HelloWorld.main(HelloWorld.java:4)




I'll post the code too in case I made a mistake whcih i haven't spotted:
public class HelloWorld {
public static void main(String[] args) {

System.out.printIn("Hello World!");
}
}

Reply
Sam
11/15/2012 8:38am

scratch that, realised it was println not printIn

Reply
Jonathan
12/11/2012 5:58pm

Does the correct placement of the brackets matter? Like does it matter where it's placed?

Reply
James C.
12/11/2012 6:07pm

Copying this from the response on Facebook. If I am not answering your question, please be more specific. You should also mention whether you mean curly braces, square brackets, or parentheses when you say "brackets" and what "correct placement" means. I am not sure if you are asking what line you can place it on, whether you can have additional spaces, or whether you can reverse the order.


"I don't know what you mean by "EXACTLY" but the main method should always look like:

public static void main(String[] args){ }
or
public static void main(String args[]){}"

Reply
Jonathan
12/11/2012 6:13pm

Another thing, when I'm creating a line of code and there's a red circled "x" to the left of it, does it mean something is incorrect?

Jonathan
12/11/2012 6:26pm

edit: okay, so i no longer have those red "x"'s, but after i hit play, should a Save and Launch dialog box pop up?

Reply
James C.
12/12/2012 12:00am

Yes. The program can't run until you save.

Reply
shavyg
12/22/2012 7:21pm

Nicely done

Reply
Adarsh
01/24/2013 8:47am

Hey James
Thanks a lot for this tutorial
I have a slight problem
When I try to run the program after entering the print line I'm getting an error
"Selection does not have a main method"
And another doubt
Is it supposed to ask everytime I try to run the program it asks me "run as" for this I get two options Java Applet and Java application
I select Java application.
I'll be waiting for a reply eagerly.

Reply
manu alwaye link
01/24/2013 10:01pm

"Selection does not have a main method":-this apper on the screen wen i tryng to run ur code in eclips

Reply
James C.
01/25/2013 6:01pm

Provide the code please!

James C.
01/25/2013 6:02pm

Run as Java Application!

Reply
Edwin link
01/25/2013 8:10am

I still dont understand what 'static' means, can u give me the example?

thank you before for amazing tuts!

Reply
James C.
01/25/2013 6:00pm

A static variable is used throughout the entire class. It only has one value. It will stay the that value as the program is being run. You will see an example later on.

Reply
Yusif Alizade link
03/30/2013 1:03am

Hi James.I want learn Android Game Development.I use your web site.But i want a book about that.Can you help me for find Android Game Development book (pdf).If you know like this book please comment. Thanks.

Reply
James C.
03/30/2013 10:52am

Yusif,

There probably are not many free .PDF versions of popular android game development books available.

Try and get a paid version of the books if possible :)

Reply
Yusif Alizade link
04/05/2013 4:54am

Thank you so much, your tutorial so good for people. and I use Java for Android . You know in Android we can use .apk file for use. but in Java i can't create .exe file for use .
can i create it ? Thanks.

vaibhav link
04/03/2013 8:54pm

i cant see the android console, there is no android console

Reply
Yusif Alizade link
04/05/2013 4:49am

Vaibhav,
you can visible console from . Window> show view> console

Reply
Yusif Alizade link
04/05/2013 4:49am

Vaibhav,
you can visible console from . Window> show view> console

Reply
akj
05/19/2013 2:31am

Thank.You for the tutorial but i find a little.difficulty in remembering definitions

Reply
wordpress website developer link
06/14/2013 10:44pm

I must say the blog post about "Game developer" is just useful for everyone else reading it because the information and knowledge it contains is very important. I like the post! Excellent job! Keep sharing such valuable information through your blogs.

Reply
Abhishek Suresh link
06/17/2013 7:36pm

Thanks a lot for the tutorial. Its really helpful. I am new to java but I have a little experience with Object Oriented Programming(C++) and your tutorial is so amazing that I am able to understand things . I only have this doubt , if you can please clear it. Is this Java tutorial of yours enough to start developing a decent android application ?

Thanks a lot for your time :) .

Reply
DonTako
06/20/2013 5:34pm

For the error "Selection does not have a main method" use this code:

public class HelloWorld {

public static void main(String trv[]) {
System.out.println("I Love Me!");
}
}


Reply
Hughrock Projects
06/29/2013 6:17pm

I understand "public" and "static" just fine, but i don't understand what "void" is all about. I know that it doesn't return a value, but that means little to me, and I'm still unsure as to its use and worth.

Void? Definition? Use? Please?

Reply
Kevin Andrada
06/29/2013 9:00pm

I think it'll be great if you can also add HTML code tags for the images so that they can be copied easily.

Thank you Kilobolt for the tut!

Reply
Kevin Andrada
06/29/2013 9:12pm

As a beginner in Java, I don't know the code println. I thought `In` was written as `capital i` and n (I was thinking camelCase) but turns out it was `small L` and n. Hehe!

Reply
Shanavas link
07/15/2013 12:35am

Simple & Awsome tutorial .

Reply
Nobray
07/26/2013 11:22pm

Amazingly explained.

Reply
surya
08/13/2013 7:02am

hey james....Thanks for ur awesome tutorials....I have downloaded eclipse latest version(i.e.,4.3).....After creating new java project...I got option src...when I gave right click on it...there is no option as new.....I am unable to find it....could u help me

Reply
David
09/07/2013 8:29pm

Quick note! The line right before: Lesson #1-4: Writing our first program has a typo on "instructions", this one:

So until you fill that togglePower method with statements (instrutions), togglePower is just a blank method.

Reply
MOn
09/21/2013 9:47pm

Hi i think this image is corrupted, https://kilobolt.com/uploads/1/2/5/7/12571940/5247921.png?671

Reply
Ryan
09/25/2013 9:36am

Hey James!

First off, I'm super excited to have come across this tutorial! I've always wanted to get into game development - particularly android since that's the operating system I use more often!

Anyways, though I'm not too far into the tutorials yet, I had a question about the program used to compile codes and such. Would Unity work instead of Eclipse? I've used Unity before and have grown comfortable with its layout. Thoughts?

I have no problem switching to Eclipse if you think it'll work better.

Hope to hear from ya!

Reply
Lukas
10/14/2013 11:47am

Hey, the tutorial is great and helps me alot getting back into Java, after starting with it a while ago, now finally out of strong interest and not because it was taught in school. My question is quite off topic though. What visual style are you using in your screenshots. I cant find it on deviantart anywhere, i really like it though. Any chance you could tell me its name?

cheers to a great tutorial

Reply
Babatbiyi
10/15/2013 4:46pm

Fanks for the tutorial man. when i type the 'printIn' it gave me an error but when I typed only 'print'. It worked. Why did this happen and can you please change it so that others wont experience such.Thanks alot guys

Reply
Victor
12/01/2013 9:46am

Almost made the same mistake: It's NOT printIn, as the word INside; it's println, letter L instead of I, like print "LiNe"

Reply
Miles
12/10/2013 8:59pm

Thank you so much for all your kindness ! Your generosity is angel level !

Reply
joresnik
12/26/2013 7:42am

I like the tutorial so far, very simplified and easy to understand (which is rare for tutorials these days for some reason).

The only thing I disagree with:
"The [] indicates that this is an array, which you can think of as a table of corresponding x and y values."

You make it sound like it's a two-dimensional array. Shouldn't they really just think of it as a list?

Reply
Johnathanth
01/03/2014 5:52pm

Thank you James for the tutotial. Like a few people, I typed printIn with a capital letter I(i), rather than small letter l (L), and got an error which stumped me for a while. If you have time, could you please clarify that it's an L, not an i, please. Thanks

Reply
muthu
02/08/2014 8:58am

HEY HI I DONT SEE THE JAVA IN THE PERSEpective menu pls help me

Reply
Atte
02/24/2014 8:00am

When i rightclick SRC and new there is not a button "java" only "javaproject" and it will just start a new project

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.