Method structure

The first part of a method that we write is called the signature. Here is a hypothetical method signature:

public boolean addContact(boolean isFriend, string name)

If we add an opening and closing pair of curly braces {} with some code that the method performs, then we have a complete method – a definition. Here is another made-up, yet syntactically correct, method:

private void setCoordinates(int x, int y){
   // code to set coordinates goes here
}

As we have seen, we could then use our new method from another part of our code, like this:

// I like it here

setCoordinates(4,6);// now I am going off to setCoordinates method

// Phew, I'm back again - code continues here

At the point where we call setCoordinates, our program's execution would branch to the code contained within that method. The method would execute all the statements inside it, step by step, until it reaches the end and returns control to the code that called it – or sooner if it hits a return statement. 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 preceding method could look like this:

int myAnswer = addAToB(2, 4); 

Clearly, we don't need to write methods to add two int variables together, but the preceding 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 returns the value stored in answer to the calling code, causing myAnswer to be initialized with the value 6.

Notice that each of the method signatures in the earlier examples varies a little. The reason for this is that the Java method signature is quite flexible, allowing us to build exactly the methods we need.

Exactly how the method signature defines how the method must be called, and how the method must return a value, deserves further discussion. Let's give each part of the signature a name so that we can break it into chunks and learn about the parts.

Tip

Here is a method signature with its parts labeled up ready for discussion. Also have a look at the table that follows to further clarify which part of the signature is which. This will make the rest of our discussions on methods straightforward:

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

And here are a few examples that we have used so far so that you can clearly find the part of the signature under discussion:

Part of signature

Examples

Modifier

public, private, protected, package-private (without modifier specified)

Return-type

int – you can also use any of the Java primitive types (such as boolean, float, and long) or any predefined reference types (such as String and class types)

Name of method

addContact, setCoordinates, addAToB

Parameters

(boolean isFriend, String name), (int x, int y), (int a, int b)

Modifier

In our earlier examples, we only used a modifier on a couple of occasions, partly because the method doesn't have to use the modifier. The modifier is a way of specifying what code can use (call) your method by using modifiers such as public and private.

Variables can have modifiers too. For example:

// Most code can see me
public int a;

// Code in other classes can't see me
private String secret = "Shhh! I am private";

Modifiers (for methods and variables) are an essential Java topic, but they are best dealt with when we are discussing the other vital Java topic we have skirted around a few times already – classes. We will do so in the next chapter.

Note

As we can see from our example methods, and the fact that all the code we have written so far works just fine, modifiers are not necessary to ease our learning, although they will be a big part of our future learning from Chapter 10, Object-Oriented programming, onward.

Return type

Next up is the return type. Like a modifier, a return type is optional, so let's look a bit closer. We have seen that our methods do stuff. But what if we need the results from what they have done? The simplest example of a return type we have seen so far was the following:

int addAToB(int a, int b){
   int answer = a + b;
   return answer;
}

Here, the return type in the signature is highlighted in the preceding code block. So, the return type is an int. The method addAToB sends back (returns) to the code that called it a value, that will then fit in an int variable.

The return type can be any Java type we have seen so far. 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 try to return a value as this will cause a compiler error. It can, however, use the return keyword without a value.

Here are some combinations of the 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 combination 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 combination:

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 preceding methods in turn, like this:

// OK time to call some methods

doSomething();
doSomethingElse();
doYetAnotherThing();
String fullName = joinTogether("Alan ","Turing")

// fullName now = Alan Turing
// continue with code from here

The preceding code would execute all the code in each method in turn.

Name of a method

When we design our own methods, the method name is arbitrary. But it is convention to use verbs that clearly explain what the method will do. Also, it is convention for the first letter of the first word of the name to be lowercase, and the first letter of subsequent words to be uppercase. This is called camel case, as we learned while learning about variable names. For example:

XGHHY78802c(){
   // code here
}

The preceding method is perfectly legal and will work. However, let's look at a much clearer example that uses the following conventions:

doSomeVerySpecificTask(){
   // code here
}

getMyFriendsList(){
   // code here
}

startNewMessage(){
   // code here
}

This is much clearer.

Now, let's have a look at parameters in methods.

Parameters

We know that a method can return a result to the calling code. But 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 already seen an example with parameters when we looked at return types. We will look at the same example, but a little more closely at the parameters:

int addAToB(int a, int b){
   int answer = a + b;
   return answer;
}

In the preceding code, the parameters are highlighted. Parameters are contained in parentheses (parameters go here), immediately after the method name.

Notice that in the first line of the method body, we use a + b as if they are already declared and initialized variables. That is because they are. The parameters of the method signature are their declaration and the code that calls the method initializes them, as highlighted in the following line of code:

int returnedAnswer = addAToB(10,5);

Also, as we have partly seen in earlier examples, we don't have to just use int in our parameters. We can use any Java type, including types we design ourselves.

What's more, we can mix and match types as well. We can also use as many parameters as is necessary to solve our problem. An example might help:

void addToAddressBook(char firstInitial, String lastName, String
city, int age){
   
   /*
         all the parameters are now living, breathing,
         declared and initialized variables.
         
         The code to add details to address book goes here.
   */
}

Now, we will look at the method body—what goes inside the method.

The body

The body is the part we have been partly avoiding, with comments such as the following:

// code here

as well as the following:

// some code

And finally the addToAddressBook method:

/*
          all the parameters are now living, breathing,
          declared and initialized variables.
          
          The code to add details to address book goes here.
   */

But, we know exactly what to do in the body already. Any Java syntax we have learned so far will work in the body of a method. In fact, if we think back, all the code we have written in this book so far has been in a method.

The best thing we can do next is write a few methods that do something in the body.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.51.241