Please share...

The Complete Java Developer Course. Learn Step by Step

The Complete Android & Java Developer Course – Build 21 Apps

Master Android N App Development With Java

Methods allow to organize and compartmentalize our code. As our game projects become more and more advanced with exiting features and deep systems then methods will be one of the programming tools that will make this manageable.

About this tutorial

Skill level 1
Time to read: 10 minutes

New Concepts:

  1. Methods
  2. Signatures
  3. Definitions
  4. Modifiers
  5. Calling methods
  6. Parameters

So what exactly are Java methods? A method is a collection of variables, expressions and control flow statements (loops and branches). The first part of a method that we write is called the signature. Here is an example method signature.

public void shootLazers(int power, int direction)

Add an opening and closing pair of curly braces with some code that the method performs and we have a complete method, a definition.

public void shootLazers(int power, int direction){
	// ZAPP!
}

We could then use our new method from another part of our code like this:

// Just going to shoot some lazers
shootLazers(100, 45) // Run the code in the method
//  I'm back again - code continues here

When we use a method we say that we call it. At the point where we call shootLazers, our program’s execution branches to the code contained within that method. The method would run until it reaches the end or is told to return. Then the code would continue running from the first line after the method call. Here is another example of a method complete with the code to make the method return to the code that called it.

int addAToB(int a, int b){

	int answer = a + b;
	return answer;

}
  • Learning java by building Android games

    Learning Java by Building Android Games

    Want to learn Java for Android? Even if you are completely new to either Java, Android, or game programming but are aiming to publish Android games, then this book is for you. This book also acts as a refresher for those who already have experience in Java on other platforms or other object-oriented languages.
    • Setup your own Android game programming environment using Android Studio
    • Control logic, branch your code, and add real decision-making depth to your games
    • Design and use 2d sprite animations, smooth pixel graphics, sound FX, simple collision detection and artificial intelligence (AI)
    • Build around a dozen sample test apps and 4 complete working games!
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US only)
    small_book

    Android Game Programming by Example

    Learn to build exciting Android game projects. Build a simple flappy-bird like game to a multi-environment, tough, retro platformer then an OpenGL ES 2 Asteroids clone, running at hundreds of frames per second .
    • Animate your characters with sprite sheets, add multiple scrolling parallax backgrounds, and implement genuinely tough, playable levels in your games
    • Every single line of code is printed in the book! No need to refer to the code files while trying to follow along. All the code files are also supplied separately so you can refer to them in their completed form and copy/paste them into your project if you like.
    • Implement a multitude of other game features such as pickups, firing weapons, HUD’s, generating and playing sound FX, scenery, level transition, high scores, and more
    Amazon USA
    Amazon UK
    Amazon CA
    Our Store (US Only)

The call to use the above method could look like this:

int myAnswer = addAToB(2,4);

As we know, we don’t need to write methods to add two variables together but the example helps us see a little more into the workings of methods. First, we pass in the values 2 and 4. In the method signature, the value 2 is assigned to int a and the value 4 is assigned to int b.

Within the method body, the variables a and b are added together and used to initialize the new variable int answer. The line return answer; does just that. It returns the value stored in  answer into the calling code, causing myAnswer to be initialized with the value 6.

Notice that each of the method signatures in the examples above vary a little. The reason for this is the Java method signature is quite flexible allowing us to build exactly the methods we require.
Exactly how the method signature defines how the method must be called and if/how the method must return a value deserves further discussion. Let’s give each part of that signature a name so we can break it into chunks and learn about them.

Here is a method signature with its parts described by their formal technical term.

modifier | return type | name of the method (parameters)

And here are a few examples we can use for each of those parts. There is one completely new concept here as well, the modifier.

Part of signature Examples

Modifier public, private
Return-type int, also use ( boolean, float, etc, any java type, expression or object)
Name of method shootLazers, setCoordinates, addAToB etc.
Parameters. (int number, String type), (int x, int y), (int a, int b)

Now let’s look at each part in turn.

Modifier

The method doesn’t have to use the modifier but the modifier is a way of specifying what other code can use your method by using modifiers like public and private. We will talk more about modifiers and reveal that in fact, variables can have modifiers too when we enter the world of Java classes and objects in a few tutorials time.

Return type

Like a modifier, a return type is optional as well.

int addAToB(int a, int b){

	int answer = a + b;
	return answer;

}

Above the return type in the signature is int. The method addAToB sends back, returns to the code that called it a value that will fit in a  int variable. The return type can be any Java type we have seen so far or one of the ones we haven’t seen yet 😉 . The method does not have to return a value at all, however. In this case, the signature must use the void keyword as the return type. When the void keyword is used the method body must not attempt to return a value as this will cause an error. It can, however, use the return keyword without a value. Here are some combinations of return type and use of the return keyword that are valid.

void doSomething(){

	// our code
	// I'm done going back to calling code here
	// no return is necessary

}

Another possibility is as follows:

void doSomethingElse(){

	// our code

	// I can do this as long as I don't try and add a value
	return;
}

The following code is yet another couple of possible methods:

void doYetAnotherThing(){
	// some code

	if(someCondition){

		//if someCondition is true returning to calling code
		//before the end of the method body
		return;
	}

	//More code that might or might not get executed

 return;

 //As I'm at the bottom of the method body
 //and the return type is void, I'm
 //really not necessary but I suppose I make it
 //clear that the method is over.
}

String joinTogether(String firstName, String lastName){

	return firstName + lastName;

}

We could call each of the methods above, in turn, like this:

//OK time to call some methods
doSomething();
doSomethingElse();
doYetAnotherThing();
String fullName = joinTogether("Corrine ","Yu")
//fullName now = Corrine Yu
//continue with code from here

Method names

The method name when we design our own methods can be almost anything at all. But it is best to use words that clearly explain what the method will do. For example:

Xvdfrsse2(){

	//code here

}

The above is perfectly legal and will work but these are much clearer:

doSomeVerySpecificTask(){

	//code here

}

getMySpaceShipHealth(){

	//code here

}

startNewGame(){

	//code here

}

Method parameters

We know that a method can return a result to the calling code. What if we need to share some data values from the calling code with the method? Parameters allow us to share values with the method. We have actually already seen an example when looking at return types. We will look at the same example but a little more closely.

int addAToB(int a, int b){

	int answer = a + b;
	return answer;

}

Above, the parameters are int a and int b. Notice that in the first line of the method body we use a + b as if they are already declared and initialized variables? Well, that’s because they are. The parameters in the method signature are their declaration and the code that calls the method initializes them.

int returnedAnswer = addAToB(10,5);

Also as we have partly seen in previous examples, we don’t have to just use int in our parameters. We can use any Java type. We can also use as many parameters as is necessary to solve our problem. Like this:

void addToAddressBook(char firstInitial, String lastName, String city, int age){

	//all the parameters are now living breathing,
	//declared and initialized variables

	//code to add details to address book goes here

}

Time to get serious about our body.

The method body

The body is the part we have been kind of avoiding with comments like:

// code here
// some code

But actually, we know exactly what to do here already. Any Java code we have learned already will work in the body of a method.

There is allot more we could learn about methods but we know enough about them already to make games. And don’t worry if all the technical terms like parameters and signatures etc. have not completely sunk in. The concepts will become clearer when we start to use them.

Let’s move on to find out about a variable type we can design ourselves by understanding OOP for coding Java games.