Methods are used to break a complex problem into small, manageable pieces.
What are Methods?
In Java, methods are subtasks within a class.
Other programming languages have different names for these, such as functions or modules, but in Java, they're known as methods.
We've already created one method in every single program that we've written, and that's the main
method. We've also been making calls to other methods, such as the Scanner
ones, to input data, and the System
one to output data.
Methods should perform a specific task and can help eliminate redundancy in code.
Let's examine the parts of a method.
The very first line of the method is called the header.
The first word in a method header is the access modifier.
Access modifiers indicate who is allowed access to use this method. public
means any code from any class can use this method. Other access modifiers include private
and protected
.
We'll talk about these in greater detail later in the course. Having an access modifier is not required. If one is not specified, then it means that this method is only accessible by classes within the same package.
The next part of the header is a non-access modifier.
This includes static
, final
, abstract
, and synchronized
. All are pretty advanced, so we won't go into detail, but we'll talk about some of these later in the course.
For now, just know that not every method requires one of these modifiers.
Next is the return type.
This indicates the data type of the value that this method will return back to the code that calls it.
This particular method's job is to calculate two numbers. It has to specify that the sum will be returned, and it will be of data type int
. That way, any method that happens to use this method, knows exactly what to expect.
Every method is required to specify a return type. If you look back to the programs that we've worked on in this course, we have the main
method, which specifies its return type of void
. Meaning, it is not going to return any value. So, even if your method returns nothing, you still have to specify a return type.
It's also important to note that a method can only return one value.
Next in the method header is the name.
Every method is required to have a name, and you should name your methods to reflect the task that they are designed to do. By convention, they should begin with a verb, like we see here, “calculate”, and optionally, adjectives or nouns can follow, such as “Sum”.
One deviation from this convention is for methods that return a boolean data type. By convention, their method names typically ask a question, such as: isSumNegative
.
Remember that by convention, all method names should begin with a lower case.
After the method names comes a set of parentheses.
This is required. Although the parentheses can be empty, if no external data is needed for the task that the method needs to complete.
Alternatively, the parentheses are used to hold a list of all the data that should be supplied to this method, if it were to be called. This is known as the parameter list, and it's formatted as a comma-delimited list of input into the method.
In this example, we need two numbers in order to be able to calculate a sum, so we specify that in the header. So, if any program were to call us to calculate the sum of two numbers, they'd have to give us the two numbers as parameters.
Every method has a signature.
The signature consists of the name of the method and the method’s parameter list.
A method signature must be unique within a class.This is how it is identified.
After the method's header, comes the method's body, which is contained within a set of curly braces: {}
The body consists of 0 or more statements that are to be executed should this method be called.
If the body has specified a return type as anything other than void
, the method must include a return
statement, that returns a value that matches the return type specified in the header.
Let's write a program that defines a method, and then we're going to call that method from our main
method.
I've created a new class called Greetings
within a new package called chapter5
.
package chapter5;
import java.util.Scanner;
/*
* OUR FIRST METHOD
* Write a method that asks a user for their name, then greets them by name.
*/
public class Greetings {
}
We need to write a method that asks a user for their name, and then greets them by name.
In the main
method, I'm going to go ahead and ask the user for their name.
Let's go ahead and get the input.
public static void main(String args[]){
System.out.println("Enter your name:");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
}
Okay, so we've gotten the user's name.
Now, we want to greet the user by name, but we're going to put that in a different method.
That is a separate task, in and of itself, to do the greeting. We're going to create a new method to do that.
To create a new method, just like we have this main
method here within the class, all of the methods have to be contained within the scope of a class. So right after the main method or anywhere — it could be before, after, it could be anywhere, it doesn't matter what order you put your methods in — we're going to add another method.
public static void greetUser(String name){
}
We put our access modifier as public
We put a non-access modifier as static
For the return
type, we won't return anything because we're just going to print something out, so we have nothing to return. Again, we still have to specify a return type though, so we put a void
.
And then we have to give it a name. Remember, the name should reflect what it's going to do, so it's going to greet the user — that's our verb, “greet”, and then the noun, “User”: greetUser
Then, it's required to have a set of parentheses, even if nothing goes inside, but in this case, we need to know the user's name to be able to greet them.
We're going to specify that if anyone calls this method, they have to pass the name, so we give it the data type of this parameter, which will be a String
and then we give the parameter a name. Essentially, this is a variable for this method, and we'll just call this name
.
Now, we put our curly braces.
So that's the header of the method.
Now, we're inside of the body, so we're going to execute the statements.
We'll just print out a statement that says, "Hi there", and then we'll add their name right here.
public static void greetUser(String name){
System.out.println("Hi there, " + name);
}
We have two methods defined in this class, the main
method and the greetUser
method.
If we were to run this class right now, it would never come into this greetUser
method because the method was never called. The way Java works is if you run a Java application, it's going to start off in the main
method. If you want another method to be executed, you have to call that method, and the way you call the method is by its name.
Main Methods Control Program Flow
The main
method is essentially used to control the flow of the program, so it'll execute everything in here.
In order to execute greetUser
, we have to type greetUser
within this main
method. And then because we are calling the method, we have to provide it with what it asks for, so we are going to provide it with the name that we just got from the input.
public static void main(String args[]){
System.out.println("Enter your name:");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
greetUser(name);
}
package chapter5;
import java.util.Scanner;
/*
* OUR FIRST METHOD
* Write a method that asks a user for their name, then greets them by name.
*/
public class Greetings {
public static void main(String args[]){
System.out.println("Enter your name:");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
greetUser(name);
}
public static void greetUser(String name){
System.out.println("Hi there, " + name);
}
}
Here’s how the flow of the execution works:
main
methodgreetUser
greetUser
method and execute everything inside this method.main
, and if we had any other statements within the main
, it would execute those as well.Let's run it. Enter your name: Angie.
Hi there, Angie.
That's how methods work.
Quiz
The quiz for Chapter 5 can be found at the end of Section 5b