Keywords: methods, void, call method, input parameters, top-down 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.
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.
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.
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.
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:
If we illustrate the different alternatives of methods
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.
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
Let’s shift focus towards what the method should return and take a closer look at two keywords:
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,
Oracle Docs tutorial()
, and a body between braces,{}
.
We’ve learned how to create methods in Java, but let’s take a couple of examples and use our new understanding.
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 } }
If we execute the program, we get the result
My first method My first method My first method
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
Let’s have a look at the third and final example for this article.
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.
What is really meant by static and non-static methods in Java? Let’s try to sort out a few differences between them.
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.
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:
Please leave feedback and help us continue to make our site better.
How useful was this article?
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?
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.
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; }
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.
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.
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.