Join Peggy Fisher for an in-depth discussion in this video Creating user-defined functions, part of Learning Java.
- A method is a group of statements used to accomplish a specific task. It is sometimes referred to as a black box. A method definition includes these parts: a method header, which contains a visibility type, public, private or protected, a return data type, a method name, a list of parameters, and the body of the method, which is enclosed in open and closing curly brackets. In the example that I have here for my project called methods, we have a main method which includes a visibility modifier of public, a return type of void, and the name of it is called main.
In parentheses, we list the arguments, a string array, and the variable name is A, R, G, S. Here is the open and closed curly brackets that indicate the block of code that's considered main. Once we have the method defined, we need to call, or invoke, the method. This is where some of the confusion can start. When calling a method from our main program, we call the method using the name and providing any necessary parameters. In this first program example, we are creating a method that calculates and returns the average of three numbers.
This methods needs the main program to send the three numbers entered by the user and the method returns a value representing the average of these numbers. Let's add our method. Outside of the main, I need to add my method. I start with the visibility modifier of public. It's also a static method because it's in the same file as the main. Now, in order to return the average of three numbers, what data type do I need to return? Hopefully you said double, because we wanna make sure we don't lose any precision. I'm gonna specify double as the return type for this method.
I give it a name. We'll call it "average." Now I need to specify what values the calling program needs to send to my method. We said that we're gonna find the average of three numbers. Let's declare three variables. double numb1, double num2, double num3. Okay. Now we can start on the body of our method. Notice I haven't finished it yet, and if I mouse over the error that's here, it's going to tell me that I'm missing my return statement.
Because I have the word "double" here, I have to have a return statement that returns a double value back to the calling program, or my program will not compile. Okay. To find the average of these three numbers, I'm gonna create a variable, double avg = ... I'm gonna add num1 + num2 + num3. And I wanna divide it by three. Don't forget, I need to add these first, so let's use parentheses to enforce our order of operations, /3; Okay. Now I have the value that I need.
Now I need to send it back to the main program. So we use the keyword "return," return avg. When I do that, my error goes away. Now let's go back up to the main, because at this point, I don't have any numbers to send to the method, and I have no way of receiving the value once they calculate the average. I said we're gonna ask the user to enter the values. Let's start by, on line seven, let's import the scanner class. Okay. In our main, let's declare our variables.
I still need a placeholder for all the variables that the user is going to enter, and so that I have the variables that I can send to my method. So I need to create additional variables here. Double ... We'll keep it simple. We'll just call them x, y and z. I also need a variable that's gonna hold the result of calling the average method. I'm gonna call it double avg. I want you to note that the avg that I defined in the main method is not the same variable as the one defined in the average method.
That's because the scope of each variable is only from the starting open curly bracket to the closing curly bracket. We'll talk more about that in a minute. Now let's ask the user to enter three numbers. I need to create a scanner object. Scanner in = new Scanner (System.int.). I need to prompt the user to enter the numbers, and then I need to read them in. So x = in.nextDouble(). y = in.nextDouble().
z = in.nextDouble(). Okay, I'm gonna scroll down a little bit. All right. Now I have the three values. I'm gonna let the method do the work for me to find the average. I'm gonna say avg = ... To call the method, I specify the name of the method, so I'm gonna use the word "average." I need to give it the values that I want it to find the average of. So in parentheses, I'm gonna give it x,y,z.
It is important to remember when you call a method, you do not specify the data type, only the variable name or a literal value. So I didn't need to specify double x, double y, or double z, because I'm actually passing the values of x, y and z to my average method. Okay. Now that I've gotten a value, I can go ahead and print it out. System.out.println, and I'll say, "The average is:" and I'll print out the value that got returned from the calling program in the variable called avg.
Of course, now that I have it written, we have to test it. Let's go ahead and test our program. Enter three numbers. I'm just gonna enter 4, 5 and 6. It says "The average is: 5.0." That makes sense. Let's test one more example. Let's try 10, 123 and 560. "The average is: 231.0." Well, it looks like our program's working. One thing I wanna note, that not all methods return values.
This one did, but they don't have to. When a method is designed to execute a block of code, but it does not return a value, such as the main method, it is considered a void method. The word void is put in the header in place of a return type. When we write methods, any variables that are defined inside the method are local and only visible for the duration of the method body. The same is true for the main method. This is referred to as the scope of the variables. This means that, even if a method is called multiple times within one program, the value stored in the method's local variables do not persist from one call to the next.
The local variables are destroyed when the method ends. The new variables are allocated memory when the method starts again. When a method is called, the program transfers control to the method and executes the statements in the body of the method. When it is done, it returns control to the calling program and continues to the next statement. In our case, we got to line 25, where we called the method average. At that point, the program jumped down to line 29, where it executed the statements inside the method avg, and then, when it was done, it returned back up to line 26.
Notice that we added the method to the bottom of our program. In Java, methods can be defined before or after the main. By using methods, we are encapsulating the process used to update and retrieve data. This is a critical component that's used extensively when we start working with classes and objects. It also allows us to break down the program into small, manageable pieces. Divide and conquer. Methods can be defined to return any data type, but they can only return one value.
In my example, I only included one method. But you can add as many methods as appropriate to help solve your problem.
- Downloading and exploring NetBeans
- Understanding Java basics: data types, strings, arrays, and more
- Controlling flow with functions and loops
- Creating classes
- Sorting and searching arrays
- Manipulating files
- Handling errors
- Building GUIs