Software Development Basics – Methods

Until now, all our code examples have been in the same Method. This is not the way it should be. In bigger projects you should create and use multiple methods. This is the topic of today’s post.

 

Methods

 

If you recall all our examples from previous posts, you see that we wrote all our code under a line of code that looks something like this

 


public static void main(String[] args)

 

This is the main method and is the method that is called when your program runs.

 

Now, we wrote all our code in the main method, but that is a bad practice. You can create your own methods to split functionality in your program. Normally, you would want a method to do a specific task.

 

Defining methods

 

This is the basic syntax to define a method

 


accessModifier returnType methodName(list of parameters){

    // code that executes in your method.

}

 

Lets explain each part of the basic syntax to define methods.

 

Access modifiers – Introduction

 

Access modifiers are reserved words that are used to set the access mode to your methods. They can also be used on classes and variables.

 

For now, consider only two access modifiers:

  • Public: a method or variable that has the public modifier, can be accessed from any class.
  • Private: a method or variable that has the private modifier, can only be accessed from within the class that contains it.

 

Return Type

 

Your methods would do some calculation or execute some lines of code. Sometimes you would want them to return a result. The return type must match the type of the result that you want to return.

 

For example, imagine you need a method that adds two integer numbers. The result would be an integer value. If you want to return this value you do something like this:

 


// Method that returns the addition of 1 + 2.

// The return type is int and it is declared as

// public. This means this method can be called

// from any class.

// Also, it does not require parameters.

public int add() {

    int result = 1 + 2;

    return result;

}

 

The return type is int. You can have any return type that you want, but you must be sure to return a value or type that corresponds to this type.

 

As you can see in the example, for returning a result you use the return keyword followed by the variable that holds your result.

 

Sometimes you need methods that don’t return a result. When this happens, you use the keyword void instead.

 


// Method that does not return a result.

public void printResult(int result) {

    System.out.println("The result is " + result);

}

 

Method Name

 

You can name your methods anything that you want. The convention is that the name would start with lowercase letters and each new word will start with uppercase letter. Also it is recommended to name your method using verbs, because they are actions that your code do.

 

List of Parameters

 

Your methods can use external values that are provided to them. These values arrive to the method as a list of parameters. This list has any number of elements – or none – separated by a comma. Each element has a data type and a variable name. These values are variables that can only be used within that specific method.

 

This example shows a list of two integer values that the method needs to work:

 


// Method that adds two values, that are passed as parameters.

public int add(int valueOne, int valueTwo) {

    return valueOne + valueTwo;

}

 

If you don’t want any parameter, just leave the two parentheses empty, like the example in the return type section.

 

As you can see in this example, you can declare variables within the method too. These variables can only be used inside the specific method where they are created.

 

Variable Parameter List

 

Sometimes you just don’t know how many parameters will be passed to a method. When this is the case, you can use a variable parameter list. When you do this, you are creating an array of parameters within your method.

 

Since this is an array, you access your parameters as you access the elements in an array.

 


// Method with a variable list of parameters.

public int add(int... parameters) {

    int result = 0;

    for (int i = 0; i < parameters.length; i++) {

        result = result + parameters[i];

    }

    return result;

}

 

This method can be called with any number of int parameters:

 


// Calling a method with variable parameter list.

result = add(50, 6, 0, 12, 3);

result = add(1, 2, 3);

 

Passing Parameters by Value

 

When your parameters are primitive values, like int, double, long etc, they are passed by value. This means that a copy is created of the original value, so within your method you work with this newly created copy, leaving the original value untouched.

 

If you modify the parameter within your method, the original value is not modified.

 


// Method that modifies a parameter passed by value.

public void modifyingByValue(int value){

    System.out.println("Received parameter value: " + value);

    value = 0;

    System.out.println("Set received parameter to zero: " + value);

}

 

If you call this method like this, you will see that the original value is kept after executing the method.

 


// Passing parameters by value

int valueToPass = 10;

System.out.println("Original value to pass: " + valueToPass);

System.out.println("Calling method...");

modifyingByValue(valueToPass);

System.out.println("Variable value after method: " + valueToPass);

 

Passing Parameters by Reference

 

Remember that I told you before that the parameter that you receive has as its scope only the method? Well, that doesn’t quite work right when you pass parameters by reference.

 

This happens when you have an Object as a parameter (more on objects in the next post). When you receive an object as parameter, then modify the values of the object, and then exit the method, you will find out that you have modified the values of the original object that was passed to the method!

 


// Method that modifies a parameter passed by reference.

// This method receives a copy of a Person object and

// modifies a value of this object.

public void modifyingByReference(Person person){

    System.out.println("Received person name: " + person.toString());

    person.setFirstName("George");

    System.out.println("Modified person name in method variable");

}

 

Calling the method like this

 


// Passing parameters by reference. You can see that if you

// modify a value of your object in the method, you will

// modify also the original object value!

Person objectToPassAsReference = new Person();

objectToPassAsReference.setFirstName("John");

objectToPassAsReference.setLastName("Lennon");

System.out.println("Person name:" + objectToPassAsReference.toString());

System.out.println("Calling method...");

modifyingByReference(objectToPassAsReference);

System.out.println("Person variable name after method: " + objectToPassAsReference.toString());

 

You can see that the name of the original object is “John Lennon”. But after entering the method and changing the first name value to the copy of the object, you get the name “George Lennon” from the original object.

 

Keep in mind this because sometimes you get weird errors in your code if you don’t have this in mind.

 

Overloading Methods

 

In our previous examples you saw two add methods, one without parameters and the other with two integer parameters. This is called method overloading: a method having the same name but different parameter list.

 

For example, if you want to add 1 + 2 in a method, two integers in another method, a variable list of integers in another method and doubles you can have something like this:

 


// Method that returns the addition of 1 + 2.

// The return type is int and it is declared as

// public. This means this method can be called

// from any class.

// Also, it does not require parameters.

public int add() {

    int result = 1 + 2;

    return result;

}

// Method that adds two values, that are passed as parameters.

// This is a method overloading since previously you have a method

// with the same name but no parameters.

public int add(int valueOne, int valueTwo) {

    return valueOne + valueTwo;

}

// Another overloaded method, this time with a variable

// list of parameters.

public int add(int... parameters) {

    int result = 0;

    for (int i = 0; i < parameters.length; i++) {

        result = result + parameters[i];

    }

    return result;

}

// Another overloaded method. This time it adds two doubles.

public double add(double valueOne, double valueTwo){

    return valueOne + valueTwo;

}

 

You cannot have two methods with the same name and the same parameter list. Also you cannot have two methods with the same name and the same parameters list but different return type. Both scenarios will cause an error.

 

Calling a Method

 

Following the previous two examples, if you want to use those methods you need to call them like this:

 


// Call a method that returns a value.

int result = add();

System.out.println("The result of the add() method is " + result);

System.out.println();

// Call a method that does not return a value.

printResult(result);

// Calling an overloaded method.

result = add(6, 9);

printResult(result);

// Calling an overloaded method with variable parameter list.

result = add(50, 6, 0, 12, 3);

printResult(result);

result = add(1, 2, 3);

printResult(result);

// Calling another overloaded method.

double doubleResult = add(6.0, 5.4);

 

You need to write the method name and provide the necessary parameters to them. And if your method returns a value you can assign that method to a variable and then make use of the returned value.

 

You can download the source code from Github

 

 

I had in mind writing about methods and classes in the same post, but it was too much about methods so I decided to split this topic in two posts. You will read about classes and objects in next post.

 

**Questions? Leave a comment or email me.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s