Keywords: methods, call method, input parameters, arguments
This article will explain how you can create and call a method in Java; in other words, how to use a method in Java. We will see several examples of using methods to form a more extensive program by creating several small methods.
When you want to use a method, it’s called that you call that method. To call a method, you enter the method name, followed by any input parameters. When an input parameter is passed to the method, it is denominated as an argument.
Therefore, to call a method in Java, we write:
If we enter the elements in the list above in the code editor
methodName (input parameters);
When we pass an input parameter to a method, it is called an argument. Moreover, when working with multiple parameters, the method call must have the same number of arguments as there are parameters in the method, and the arguments must be passed in the same order.
For example, if you have the method below
public static void exMethod (int a, String b, double c){ }
All arguments into the method must be declared and in order int, String and double. Similarly, if the method has no input parameters, we can, of course, not specify any.
Therefore, if our method does not require any input arguments we simply leave the parentheses empty
// No input arguments to the method public static void exTwoMethod (){ }
Dividing a complex problem into smaller parts makes your program clear to understand and reusable.
If the method returns a value, you can assign this to a variable of the same data type. Therefore, if we have a method that returns something and want to save it in a variable, we declare:
// Assign the values that the method returns to a variable datatype variableName = methodName (input parametrar);
Important to pay attention to the data type that the method returns. Remember, if we want to save values in a different data type than the method returns, we can use type conversion to convert our data type to a suitable type.
Now we’ve seen how to create and call methods in Java, but let’s take a couple of examples to use what we have learnt.
Let’s start with a simple example. Below we have created a method named my_method. We have specified that my_method should return an int and have two input parameters, num1 and num2, of data type int. Additionally, the method performs a multiplication between num1 and num2 and then return the value.
public class Exempel { // Method that multiply two numbers public static int my_metod(int num1, int num2){ return num1 * num2; } }
Furthermore, if we illustrate the method
We can now call the method by using the name of the method:
public class Exempel { // Method that multiply two numbers public static int my_metod(int num1, int num2){ return num1 * num2; } public static void main(String[] args) { int a = my_metod(5, 4); // Uses the method and prints the answer System.out.println("Result from my_method: " + a); } }
In this case
Let’s try a few more cases.
public class Exempel { // Method that multiply two numbers public static int my_metod(int num1, int num2){ return num1 * num2; } public static void main(String[] args) { int a = min_metod(5, 4); int b = min_metod(3, 2); int c = min_metod(1, 8); // Uses the method and prints the answer System.out.println("Result a from my_method: " + a); System.out.println("Result b from my_method: " + b); System.out.println("Result c from my_method: " + c); } }
If we run our program we get the result
Result a from my_method: 20 Result b from my_method: 6 Result c from my_method: 8
If you want to try the example above, use the button below to try it online.
In this example, we will programme a calculator that keeps track of how many people are inside a store (a very relevant use during the Covid-19 pandemic). Furthermore, we will use the built-in scanner class to gather information from the user.
Let’s start with a straightforward method, all it has to do is add one person
// Increase the variable nmbrOfPeople by one public static void increaseValue(){ nmbrOfPeople++; }
Similarly, we create a method that will remove a person
// Reduces the nmbrOfPeople variable by one public static void decreaseValue(){ nmbrOfPeople--; }
Additionally, we also want a method that returns the value of nmbrOfPeople
// Returns the value of nmbrOfPeople public static int getNmbrOfPeople(){ return nmbrOfPeople; }
Moreover, we also write a method that asks the user questions. If the user writes “INCR“, the number of people in the store will increase. Correspondingly, if the user writes “LOW“, the program should lower the number of people in the store.
// This method returns the input from the use // In this case, a String is returned public static String getInputsFromScanner() { String name; // Asking the user to increase or decrease System.out.println("Type INCR if you want to increase the number " + "people, or type LOW to reduce the number of people"); // Create a scanner object Scanner input = new Scanner(System.in); // Save the input from the user name = input.nextLine(); // The method return the variable name return name; }
Finally, let’s combine all the methods to build our program
//Import the Scanner class import java.util.Scanner; public class Counter { //Creates the variable nmbrOfPeople public static int nmbrOfPeople = 0; // Increase the variable nmbrOfPeople by one public static void increaseValue(){ nmbrOfPeople++; } // Reduces the nmbrOfPeople variable by one public static void decreaseValue(){ nmbrOfPeople--; } // Returns the value of nmbrOfPeople public static int getNmbrOfPeople(){ return nmbrOfPeople; } public static String getInputsFromScanner() { String name; System.out.println("Type INCR if you want to increase the number " + "people, or type LOW to reduce the number of people"); Scanner input = new Scanner(System.in); name = input.nextLine(); return name; } public static void main(String args[]) { // Boolean variable to control the loop boolean runProg = true; //The loop run while runProg is true while(runProg) { // The getInputsFromScanner method returns the value of //what the user enters and saves it in str String str = getInputsFromScanner(); // If user typed "INCR", the increaseValue method should run if (str.equals("INCR")) { increaseValue(); } // If user typed "LOW", the decreaseValue method should run else if (str.equals("LOW")){ decreaseValue(); } // If the user entered "QUIT", the loop should end else if(str.equals("QUIT")){ System.out.println("The program ends"); runProg = false; } //If the user entered incorrect input else{ System.out.println("Incorrect input, try again"); } //Finally, we show the number of people in the store System.out.println("Number of people in the store: " + getNmbrOfPeople()); } } }
To conclude, we have used several different methods to create a full program. Small building blocks together create big programs. Therefore, make your methods as general and useful as possible so that you can reuse them as many times as possible.
Our third and final example will be perhaps a bit longer, but let us take it step by step. Our third and final example will be perhaps a bit longer, but let us take it step by step. In this example, we will use methods to write a program that calculates the volume of a cone and a pyramid. The program should then determine which of the cone or pyramid has the largest volume. Additionally, we will use JOptionPane to create dialogue boxes that will interact with the user.
First of all, the volume of a cone is calculated with the formula:
where B is the base surface of the cone and h is the height. The base area is calculated with:
In other words, the area of the circle formed in the cone.
Furthermore, the volume of a pyramid is calculated by the formula:
B is the base surface of the pyramid and h is the height. The base area is calculated as the length of the triangle formed, multiplied by the width of the triangle.
Let’s start by creating a method, areaCircle, that calculates the area on a circle, in other words, the cone’s base area. The method has a data type double as an input parameter and should also return a double.
public static double areaCircle(double radius) { // Calculate the area of a circle double area = radius*radius*Math.PI; return area; }
Similarly, we create a method, areaPyramid, that calculates the base area for the pyramid. Note that areaPyramid takes two input parameters of data type double and that the method also returns a double
public static double areaPyramid(double length, double width ) { // Calculate the base area of pyramid double areaTriangle = length*width; return areaTriangle; }
Furthermore, since the formula for calculating the volume is the same on both the cone and the pyramid – we can use the same method. Therefore, we do not need to write one method for the cone and one for the pyramid. Instead, we use the same method.
We create a method named volume which also takes two values (area and height) and then returns a data type variable double.
public static double volume(double area, double height) { // Calculate the volume double volume = area * height; return volume; }
Furthermore, to distinguish which of the volumes that is the largest, we will create a method named largestVolume. Note that the method largestVolume returns a String.
public static String largestVolume(double volumeCone, double volumePyramid){ // Evaluate if the cone's volume is larger than the pyramid's if(volumeCone > volumePyramid){ return "The cone has the largest volume"; } // Evaluate if the cone's volume is smaller than the pyramid's else if(volumeCone < volumePyramid){ return "The pyramid has the largest volume"; } // Else, the volumes must be the same size else{ return "The volumes are the same size"; } }
Finally, we create a method that receives the pyramid’s length and height and the cone from the user by utilising the JOptionPane class. The method is named getInputsFromJOptionPane and should not return any value (void), nor should the method receive any input parameters.
public static void getInputsFromJOptionPane() { // Saves the value that the user enters in a dialog box // Double.parseDouble exists so that the value entered is a double double radiusCone = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the radius of the cone")); double heightCone = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the height of the cone")); double lengthPyramid = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the length of the base of the pyramid")); double widthPyramid = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the width of the base of the pyramid")); double heightPyramid = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the height of the pyramid")); // Use the areaCircle method to calculate the area. Submits the value of radiusCone. // The value returned from the method is saved in areaOfCone double areaOfCone = areaCircle(radiusCone); // Use the method volume to calculate the volume of the cone. Submits the value of areaOfCone and heightCone. double volumeCone = volume(areaOfCone, heightCone); // Use the areaPyramid method to calculate the area. Submits the value of lengthPyramid and widthPyramid. double areaOfPyramid = areaPyramid(lengthPyramid, widthPyramid); // Use the volume method to calculate the volume of the pyramid. Submits the value of areaOfPyramid and heightPyramid. double volumePyramid = volume(areaOfPyramid, heightPyramid); // Determine volume is largest using the largestVolyme method. String largestVolume = largestVolume(volumeCone, volumePyramid); // Prints the largest value in a dialog box JOptionPane.showMessageDialog(null, largestVolume); }
To conclude, if we merge the code from all the previous steps with associated explanatory comments, we get:
//Import the class JOptionPane import javax.swing.JOptionPane; public class Volume { public static void main(String args[]) { // This is where the code starts. // The getInputsFromJOptionPane method is executed first getInputsFromJOptionPane(); } public static double areaCircle(double radius) { // Calculate the area of a circle double area = radius*radius*Math.PI; return area; } public static double areaPyramid(double length, double width ) { // Calculate the base area of pyramid double areaTriangle = length*width; return areaTriangle; } public static double volume(double area, double height) { // Calculate the volume double volume = area * height; return volume; } public static String largestVolume(double volumeCone, double volumePyramid){ // Evaluate if the cone's volume is larger than the pyramid's if(volumeCone > volumePyramid){ return "The cone has the largest volume"; } // Evaluate if the cone's volume is smaller than the pyramid's else if(volumeCone < volumePyramid){ return "The pyramid has the largest volume"; } // Else, the volumes must be the same size else{ return "The volumes are the same size"; } } public static void getInputsFromJOptionPane() { // Saves the value that the user enters in a dialog box // Double.parseDouble exists so that the value entered is a double double radiusCone = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the radius of the cone")); double heightCone = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the height of the cone")); double lengthPyramid = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the length of the base of the pyramid")); double widthPyramid = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the width of the base of the pyramid")); double heightPyramid = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the height of the pyramid")); // Use the areaCircle method to calculate the area. Submits the value of radiusCone. // The value returned from the method is saved in areaOfCone double areaOfCone = areaCircle(radiusCone); // Use the method volume to calculate the volume of the cone. Submits the value of areaOfCone and heightCone. double volumeCone = volume(areaOfCone, heightCone); // Use the areaPyramid method to calculate the area. Submits the value of lengthPyramid and widthPyramid. double areaOfPyramid = areaPyramid(lengthPyramid, widthPyramid); // Use the volume method to calculate the volume of the pyramid. Submits the value of areaOfPyramid and heightPyramid. double volumePyramid = volume(areaOfPyramid, heightPyramid); // Determine volume is largest using the largestVolyme method. String largestVolume = largestVolume(volumeCone, volumePyramid); // Prints the largest value in a dialog box JOptionPane.showMessageDialog(null, largestVolume); } }
Följande är några enklare misstag som vi uppmärksammat
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?
When you want to use a previously declared method, it’s called that you “call that method”. To call a method, enter the name of the method followed by any input parameters in parentheses. When a parameter is passed to the method, it is called an argument. Additionally, when working with multiple arguments, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order. Finally, if the called method returns a value, it can be assigned to a variable of the same data type.
methodName (input parameters);
By entering the name of the method followed by the method’s arguments in parentheses.
These are the input parameters that the method uses. When we send a parameter to the method, it is called an argument. If you have multiple arguments, the method call must have the same number of arguments as there are parameters and the arguments must be sent in the same order.
Yes. In Java, methods can call themselves; this is called recursion and is an effective way to work with methods. Recursion is a process in which a method calls itself, directly or indirectly, and the corresponding function is called a recursive function. We will have a closer look at recursive methods in the next article.
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?