Skip to content

Methods

A method is a block of code enclosed with a descriptive name that describes what the enclosed code collectively does. It can be run by invoking the method name elsewhere in the project. The methods are compelling programming features that abstract a highly complex block of code down to a single method name.

In this code note, we will cover following topics:

  • Benefits of Method
  • Method Structure
  • Creating Methods
  • return keyword
  • Method Signature



› Benefits of Method

Advantages of defining methods in a program are:

  • It organizes repeating code.
  • It enables the creation of a reusable code block
  • It can be called numerous times and in multiple different places in the project.
  • Users can input data for processing into the method.
  • It will return processed data to the users.

Instead of writing test case like this:

without using a method
@Test
public void testCase() {
    int number1 = (int)(Math.random() * 500);
    System.out.println(number1);

    int number2 = (int)(Math.random() * 500);
    System.out.println(number1);

    int number3 = (int)(Math.random() * 500);
    System.out.println(number3);

    int number4 = (int)(Math.random() * 500);
    System.out.println(number4);
}

You can write simple test case like this:

with using a method
@Test
public void testCase() {
   for(int i = 0; i < 4; i++) 
        getRandomNumber();  // <-- using method
}

// Method 
public void getRandomNumber() {
    int number = (int)(Math.random() * 10000);
    System.out.println(number);
}



› Method Structure

Different parts of the Java method:

Following dropdowns explains each part of the method:

Access Modifier
  • Determines whether other codes in the same project can use this method.
  • It has a few variants: public, private, protected, which we will learn later.
Return Data Type Specification
  • Shows the type of data returned from the method to the user.
  • Use void to indicate the method does not return any data to the user.
Method Name
  • The name of the method should describe what the enclosed code collectively does.
  • Naming rules and conventions are the same as variables.
Parameters
  • Temporary variables used for storing input data values provided by the method caller.
  • Do not list any parameters if the method does not need input data from the user
Method Body
  • It consists of zero or more statements (executable code).
  • It starts with code open block { and ends with closing code block }.



› Creating Methods

You can create 4 types of methods in Java. They are distinguished by whether or not they take input data from the user. Also, whether or not they return processed data to the method user.

Code example: Creating Method

Example of creating 4 different types of methods.

1
2
3
4
5
6
7
// no parameter, no input data  
// return no data since it has "void" keyword 
public void saySomething10Times() {
    for (int i = 0; i < 10; i++) {
        System.out.println("hello Leaf!");
    }
}
1
2
3
4
5
6
// no parameter, no input data  
// returns one intger data 
public int getRandomNumber() {
    int num = (int)(Math.random() * 100);
    return num;
}
1
2
3
4
5
6
7
// asks for one input data ( integer )
// returns no data since it has "void" keyword 
public void saySomething(int count) {
    for (int i = 0; i < count; i++){
        System.out.println("hello Leaf!");
    }
}
1
2
3
4
5
6
7
// asks for one input data ( integer )
// returns one intger data 
public int getRandomNumber(int limit) {
    limit++;
    int num = (int)(Math.random() * limit);
    return num;
}

Code example: Method Calling

In the same Java document, we can use the methods we have created by simply invoking its method name and providing input data.

// ======  main: We are calling or using 4 methods ======== //

@Test
public static void main(String[] args) {
    saySomething10Times();           // calling TYPE 1: prints "hello Leaf!"" to the screen.
    int rand = getRandomNumber();    // calling TYPE 2: generates & returns a random number, and it was stored into "rand" 

    saySomething(10);                // calling TYPE 3: prints "hello Leaf!" 10 times to the screen.
    int random = getRandomNumber(20);// calling TYPE 4: generates & returns a random number [0~20], and stored into "random"
}



› Method Parameters

The method parameters are used for storing users' input data value to the method. Without parameters, creating a robust method is not possible as we have to create many methods that cover all the possible user input data one by one. Consider the following example where getRandomNumber(int) is invoked inside the main method.



return Keyword

Java has a special keyword for exiting a method with data. It is the return keyword, which can only be used inside the method.

Consider the canIvote(29) method below. Whenever Java finds this method name, it will get into the method body to execute the block of code. Whenever a return keyword is encountered, the Java will exit from the method body and goes back to the method call statement.

Inside the method, we can put the data we would like to give back to the caller right after the return keyword. However, the type of data we put must match with the specified Return Data Type Specification of the method.

List of scenarios when the Java will exit from a method:

Java would exit from the method body during code execution if any of this took place.

  • End of the method is reached: no more code remains in the method that needs to be executed.
  • return statement encountered: return statement has been encountered with data return 19; or without data return; it will exit.
  • Error or Exception occurs: method abruptly exits when executed code results in an error.



› Method Signature

When you create methods, be careful not to duplicate them. It will result in programming errors since Java cannot decide which one of them to execute. However, simply having two methods with identical names does not make them a duplicate method.

In Java, two methods are only considered duplicate if and only if all of the following four properties are exactly the same between them. These four properties are collectively known as the method signature:

  • 📛  Method Name
  • 🔢  Number of parameters
  • 💠  Data Type of each parameter
  • 💠  Appearing order of each parameter

The following methods are all different, except for the last one. Please read the comments for detailed explanations

unique method example
// ========= Different & Unique Method =======//
public void addOnePassenger(){
    // This method has 0 parameter
}

public void addOnePassenger(Person person){
    // This method has one parameter of type "Person"
}

// METHOD #: 3
public void addOnePassenger(int bags){
    // This method has one parameter of type "int"
}

public void addOnePassenger(Person person, int bags){
   // This method has two parameters of type "Person" and "int"
}

public void addOnePassenger(int bags, Person person){
    // This method has two parameters of type "int" and "Person"
    // Order of parameter is different than above method
}

public void addOnePassenger(int bags, int carryOns){
   // This method has two parameters of type "int" and "int"
}

// ========= Duplicate Methods =======//
public void addOnePassenger(int carryOns){
    // This method has one parameter of type "int"
    // ERROR:  this method is duplicate of METHOD #: 3
}

There is a Java programming concept called Method Overloading that uses method signature heavily; however, we will learn them in later sessions.