Methods in Java: powerful tool for reusing and structuring your code


Keywords: methods, void, call method, input parameters, top-down programming

Method Java Programming

This chapter will cover methods in Java that are a way to reuse and structure our code. The chapter on methods will show why we should use methods and the syntax used for creating and using them. Additionally, the chapter ends with a more extended example that explains how we can use several different methods when we build our programs.

Methods in Java

When programming, it is common that we want to reuse our code several times and structure it in several components. To achieve that, we have methods. By creating several smaller methods in Java, these can be used to combine to an extensive program.

This chapter contains the following articles where we will first learn what a method in Java is, and then go ahead and create and call a number of different methods with a longer example. Finally, we will also take a closer look at what is meant by recursive methods and what it means when a method calls another method.

Pages

What is a method in Java? 

A method in Java performs a code block; in other words, a sequence of operations, every time you use the method. Using a method is called calling the method, and the results from that call are referred to what the method returns. Methods in Java is a useful and powerful tool because methods are completely independent of other code and can be called from several different classes. You can pass data, known as parameters, into a method.

You can imagine a method like a black box. First, you assign one or more values to the box and then get another value back, but you do not need to know what is happening inside the black box. 

Method Java programming

Figure 1: Method in Java

In other words, you do not need to know how the code is programmed that generates the output of the input. The important thing is that you know what happens when you call the method. This abstracts the program and creates a more compact program.

How methods in Java work? 

A method in Java can be structured in a couple of different ways. On the one hand, you can choose whether the method should take in information, in other words, if the method should take any input. But also what should come out of the method, quite simply, what the method returns and what will be the result when we use the method. 

Therefore, in general, we can say that we need to state two things when we create the method:

  1. Number of input parameters. It can be anything from no input parameters to several different input parameters.
  2. What the method returns. Similar to the input parameters, we can state that the method should return a value, or that it simply does not return anything at all.

If we illustrate the different alternatives of methods

Methods Java programming

Figure 2: Different methods in Java

How create a method in Java

As mentioned in the paragraph above, there are several different alternatives for methods. Hence there is no unambiguous syntax for how to create a method. Therefore, let’s try to take it as general as possible and then break down each part step by step.  

Syntax: Declaring a method in Java

If we state a general syntax for a method in Java: 

public static return_datatype name(input_datatype nameA, input_datatype nameB, ...) {

    // The methods code block

    // The method ends with return
    return variable_return;  
}

Let’s take a closer look at the ”head” of the method 

Syntax: Input parameters for method in Java

  • public static – is the so-called modifier that determines the visibility of the method. We will explain the difference between static and non-static below. 
  • return_datatype – specifies the data type that the method should return. For example, an int, double or string. It is possible to return all of the data types we have seen in previous chapters. Additionally, if no data type should be returned, use the reserved word void
  • name – is the name of the method. All methods must have a name and best practice is that the name is always written in lower case.
  • (input_datatype nameA, input_datatype nameB, .. ) –  inside the parentheses, you enter the input parameters for the method. Simply put, what is it you want to send in as information to the method. Each input parameter is specified with the data type and name and then separated by a comma. You can specify any number of input parameters for a method. However, if you leave the parentheses empty, you do not submit any value into the method.

Syntax: Return from a method in Java

Let’s shift focus towards what the method should return and take a closer look at two keywords: 

  • void — a method that has void specified will not return any value. As we saw before, when we do not want our method to return something, we define it in the “head” of the method.
  • return — all methods (except those defined with void), must return a value. It is the keyword return that indicates what we return out of the method. In the code we wrote above, we return the value variable_return. It is important to note that what we want to return must be the same as the data type specified when we created the method. In other words, we must return a data type of what we called return_datatype in the code we wrote above. For example, if return_data type would be the data type int, then we can not return a string, even if it would be the case that we have both an int and a string as input parameters.

A method always ends immediately after return has been executed. Meaning, it’s always the last thing that happens in the method. 

The only required elements of a method declaration are the method’s return type, name, a pair of parentheses, (), and a body between braces, {}.

Oracle Docs tutorial

Examples: Methods in Java

We’ve learned how to create methods in Java, but let’s take a couple of examples and use our new understanding. 

Example 1: Create a method in Java that prints a text string

We will start with a simple example where we create a method that should print a text every time it is called.

public class Exempel {

    // Creates a method called my_method
    public static void my_method(){
        System.out.println("My first method"); 
    }

    public static void main(String[] args) {
        my_method();  // Call method
        my_method();  // Call method
        my_method();  // Call method
    }
}
  • What we have initiated above is that we have created a method named my_method.
  • my_method is a void method, which means it will not return anything.
  • Additionally, my_method does not take any input parameters. Therefore, the method has no input and also does not return anything.
  • Finally, to use my_method that we just created, we call it by writing the method’s name followed by the input parameters that the method should receive. 

If we execute the program, we get the result

My first method
My first method
My first method

Example 2: Declare a method in Java that sums two numbers

In this example, we will create a method that will take two integers as input parameters; then the method should add the two numbers and return the result as a double. 

In other words, two integers as input and return a double. 

public class Exempel {

    // Method that adds two numbers
    public static double addNumbers (int a, int b){
        return (a + b);
    }

    public static void main(String[] args) {
        // The two input parameters to the method
        int inputA = 10;
        int inputB = 4;
        
        // Uses the method and prints the answer
        System.out.println("Result from method: " + addNumbers(inputA,inputB));

    }
}

If we execute the program in example 2, we get the result

Result from method: 14

Example 3: Method to see if the provided code is correct

Let’s have a look at the third and final example for this article.

  • We will code a simple program that will compare if the user’s code matches the pre-specified code 4698.
  • We will use a method that compares the user input to the prespecified code and return a boolean variable. 
  • Additionally, we will print the result, in other words, if the entered code is correct or not. Since this article focuses on methods, we will create a method for each printout in the terminal. 
  • Finally, we will use the built-in scanner class to retrieve information from the user.

Let’s use the given instructions and write our program

// Import the Scanner class
import java.util.Scanner;

public class Exempel {

    // Method to validate the code
    public static boolean checkEntCode (int userIn){

        if (userIn == 4698){
            return true;
        }
        return false;
    }

    // Method to print info at the correct code
    public static void printOpen (){
        System.out.println("Correct code : Door opens");
    }

    // Method to print info if wrong code
    public static void printClosed (){
        System.out.println("Wrong code : Door locked");
    }

    public static void main(String[] args) {

        // Ask the user to enter information
        System.out.println("Enter code: ");

        // Creates a scanner object
        Scanner input = new Scanner(System.in);

        // Save the input from the user
        int userIn = input.nextInt();
        
        /* Uses the method above to validate
         if the code is correct */
        if (checkEntCode(userIn)){
            printOpen();
        }
        else{
            printClosed();
        }
    }
}

To conclude, in this case, it becomes tricky to print what the answer is because it depends on what the user enters. Therefore, feel free to copy the code and test it yourself.

Difference between static and non-static method in Java

What is really meant by static and non-static methods in Java? Let’s try to sort out a few differences between them.

  • One of the major differences between a static and a non-static method is that a static method belongs to a class while a non-static method belongs to the instance. This means that you can call a static method without creating an instance of the class. It probably sounds unclear now, but we will see more about classes and instances later.
  • A rule of thumb that can be used: “does it make sense to call this method, even if no object has been instantiated yet?” In that case, it should definitely be a static method.
  • Another important difference between static and non-static methods is that you can not use a non-static method variable in a static method; you can not even call a non-static method from the one static method. However, the opposite works, for example. You can call a static method from a non-static method in Java.

In conclusion, the static concept is in general always experienced with some ambiguity by new Java programmers, especially in the beginning. But do not worry, it will become more evident the more we learn about classes and objects. In our examples in this chapter we will only use static methods.

Why use a method in Java?

To reuse code: define the code once, and use it several times. A major advantage of methods in Java is that you do not have to type the same code multiple times. You can call a method instead. Methods are a powerful tool because they are completely independent of other code. One method may also call another method. 

In short, methods in Java: 

  • Performs a block of operations when you call it, which means that instead of rewriting the same code multiple times. We can instead reuse code and run it numerous times.
  • A method can receive one or multiple values, so-called input parameters, and can also return values.
  • By return, meaning what the method “is giving back” when it has performed the operations. The method always ends when the method has returned the values

When should I use a method in Java?

  • Reusable code: If you need to do the same thing (or almost the same thing) many times over, write a method to do it, and then use that method every time you perform that task. 
  • Top-down programming: A beneficial approach in programming is called top-down programming. You solve a big problem, which is seen as the “top”, by breaking it down into smaller problems. 
  • Visualise the problem: Use methods to break down the task in your mental picture of the problem, making it much easier for you to work with your programs if you break them down and try to visualise them in smaller parts. 
  • Simplify: Sometimes, we do not need to know how a method works; we are only interested in what it does. This means that, as mentioned earlier, we can focus on the main problem and focus on what our methods produce, rather than how they do it.

Summary: Methods in Java

Methods in Java is a powerful tool for reusing and structuring our code. We can use methods to simplify and break down our programs into smaller parts, and then solve the smaller pieces that together build the complete solution. Moreover, using a method is denominated as calling it, and the result of that call is named what the method returns. When you declare a method, you need to specify the input parameters the method should receive and use and what the method should return. 

Syntax: Declaring a method in Java

If we state a general syntax for a method in Java: 

public static return_datatype name(input_datatype nameA, input_datatype nameB, ...) {

    // The methods code block

    // The method ends with return
    return variable_return;  
}

FAQ: Methods in Java

What is a method in Java?

A method in Java performs a code block; in other words, a sequence of operations, each time you use the method. Methods is a tool that helps us reuse and structure our code.

What does the keyword void mean in a method?

If no data type is to be returned from the method, we use the reserved word void. Hence, if we don’t want our method to return anything, we should use a void method.

Can a method have multiple different input parameters?

Yes. Every input parameter is specified with the data type and name and then separated by a comma. You can define any number of input parameters for a method.