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.
[widgets_on_pages id=”udemy_advert_java_1″][widgets_on_pages id=”udemy_code_details”]

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;

}

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 is 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

[widgets_on_pages id=”udemy_advert_java_3″][widgets_on_pages id=”udemy_code_details”]

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.