So far in this series, all of our code has gone in the main method. A method is a block of code that gets executed when it’s called and is associated with a particular object or class. It’s a slightly more specific type of function, which is a block of code that is just executed when called (but may not be associated with a particular object). You may hear these blocks referred to somewhat interchangeably as functions or methods, but as far as Java is concerned, the proper term is method, since Java’s object-oriented.
As you know by now, the main method is the first method to run in any Java program. We can create additional methods to better organize our code and to encourage reusability of code. For example, if we need to do the same thing multiple times, rather than rewriting the same code multiple times, we can just have a method that does that particular thing each time, and call it whenever needed.
We’ve already been calling other methods provided to us by the objects in the Java API. In the previous chapter, we added BigDecimals using the BigDecimal.add() method. To print messages to the console, we’ve been using the System.out.println() method. Methods can take parameters which are variables in a method definition that the method can act on. When variables are being passed to a method, they are called arguments. We discussed this briefly in Chapter 2.
Let’s look at the println method. When we call it with the System output stream (System.out), we are giving it a String as an argument. The println method then handles the work of printing the message to the screen, so we don’t have to worry about writing our own println method from scratch every time we want to print a message. It’s already there for us.
System.out.println("Hello, World.");
Code language: CSS (css)
In this chapter, you will learn how to create your own methods with their own parameters. We’ll begin with a basic method with no parameters and go from there.
Void Methods
Some methods process information and return a value or an object. An example would be the BigDecimal arithmetic functions, which return a new BigDecimal with the new value, as was discussed in the previous chapter. A void method is a method that doesn’t return a particular value. It just executes a set of code. So the main method in our Java programs is a void method. Since it’s the main method, there’s nowhere to return to. When it’s done executing, the program stops.
Create a new Java project. Don’t worry about putting anything in the main method for now. We’re going to be creating a new method called printHello() which simply prints out the message Hello, World. We’ll then call the printHello() method from the main method, and see if it works. Note that the convention for naming methods is camelCase. The name we give our methods should be descriptive of what the method does.
Outside of the main method, preferably underneath it, but not outside of the class, create a new static void method called printHello() as follows:
public class Main {
public static void main(String[] args) {
//your code here
}
static void printHello(){
System.out.println("Hello, World.");
}
}
Code language: JavaScript (javascript)
We need to use the keyword static because the main method is static. A static method is a method which belongs to a class, but not an instance of the class. This has to do with the scope of the method. The scope of a method or variable dictates where and how we can access it, and affects where things are stored in the computer’s memory. We will discuss scope and static methods in more detail in a later chapter, when we get deeper into object oriented design. For now, just understand that since the main method is static, all the methods we directly call from it must also be static. In this chapter, we will place all our new methods in the same class as the main method, so the scope of these methods will be limited to this single class.
We declared the method as void using the void keyword.
Now that we have created our first non-main method, let’s try it out. Simply add the line printHello(); to the main method to call the printHello method.
public class Main {
public static void main(String[] args) {
printHello();
}
static void printHello(){
System.out.println("Hello, World.");
}
}
Code language: JavaScript (javascript)
When we run it, we get:
Hello, World.
Accepting Parameters
Now let’s create a slightly more complex method that actually does something using parameters. We define our method parameters by adding parenthesis after the method identifier, and then declaring variables within this definition. Create another method called “sayHiTo” outside of the main method, but still within the same class, that accepts a String called name as a parameter. We will then print out Hello, followed by whatever String value was given to us.
static void sayHiTo(String name){
}
Code language: JavaScript (javascript)
When we declared the String identified as name in the method declaration, we are limiting the scope of this variable to this method alone. Since the String name is outside the main method, we can only use this variable within the sayHiTo method. If we declared a second String name in the main method, it would be an entirely separate variable from the String name of the sayHiTo method.
Take this name parameter and have it print out “Hello, name”.
static void sayHiTo(String name){
System.out.println("Hello, " + name);
}
Code language: JavaScript (javascript)
Now return to the main method. We now can use the sayHiTo() method to say hi to anyone. For example, if I wanted to say hi to myself, I would add the String “Kevin” to the method’s argument when I call it from the main method.
public static void main(String[] args) {
printHello();
sayHiTo("Kevin");
}
Code language: JavaScript (javascript)
The output is:
Hello, World.
Hello, Kevin
We can now use this sayHiTo method to say hello to whoever we want. I have added a few more method calls with different names. My entire class file now looks like this:
public class Main {
public static void main(String[] args) {
printHello();
sayHiTo("Kevin");
sayHiTo("Samantha");
}
static void printHello(){
System.out.println("Hello, World.");
}
static void sayHiTo(String name){
System.out.println("Hello, " + name);
}
}
Code language: JavaScript (javascript)
The output is:
Hello, World.
Hello, Kevin
Hello, Samantha
A Note on Stack Memory
Recall from the previous chapter when we discussed that Java loads each method as a new frame in stack memory, and executes them one at a time. The above code printing out names could be visualized like this:
Custom Addition Method
Now let’s create another method that adds two doubles together and prints their result. We’ll call it the printSum method. We can add as many parameters to a method as we’d like by simply separating them with commas in the method declaration. In the example below, we take two variables as parameters, the double x and double y, add them together in a variable called sum, and print out the result.
Note that the scope of the variable sum is limited to this one method, the same way x and y are limited to this method. We cannot go back to the main method and use this same variable “sum” as it has not been declared within the scope of the main method. Additionally, each time this method is called, the variable “sum” is re-initialized each time, and thrown out when the method finishes executing. So when we call the printSum() method multiple times, it’s creating a new “sum” variable each time.
static void printSum(double x, double y){
double sum = x + y;
System.out.println("The sum of " + x + " and " + y + " is: " + sum);
}
Code language: JavaScript (javascript)
Test it out by calling it from the main method and passing two doubles as arguments.
public static void main(String[] args) {
printSum(10.5,3.4);
printSum(2,2);
}
Code language: JavaScript (javascript)
The sum of 10.5 and 3.4 is: 13.9
The sum of 2.0 and 2.0 is: 4.0
Overloaded Methods
Method overloading is the ability to create multiple methods with the same name and different parameters. This allows us to create multiple methods that do something similar, but handle different types of parameters as the input data. A method with multiple definitions is said to be overloaded. Continuing on from the last printSum() method, let’s create an additional printSum() method that accepts three doubles as parameters and prints the result.
Create a second printSum() method below the first one as follows:
//overloaded printSum method taking 3 params
static void printSum(double x, double y, double z){
System.out.println("Overloaded method was used.");
double sum = x + y + z;
System.out.println("The sum of " + x + " and " + y + " and " + z + " is: " + sum);
}
Code language: JavaScript (javascript)
Java is intelligent enough to know that when we call the printSum method now and use 3 arguments instead of 2, to use the second printSum method instead of the first:
public static void main(String[] args) {
printSum(10.5,3.4);
printSum(2,2);
printSum(1,2,3);
}
Code language: JavaScript (javascript)
The sum of 10.5 and 3.4 is: 13.9
The sum of 2.0 and 2.0 is: 4.0
Overloaded method was used
The sum of 1.0 and 2.0 and 3.0 is: 6.0
You can also create overloaded methods using the same number of parameters, but different variable types in the parameters. Java will see what types you used when called and execute appropriately.
Add a third printSum() method that takes two ints as parameters.
My entire class file now looks like this (I’ve added another line to the main method as well)
public class Main {
public static void main(String[] args) {
printSum(10.5,3.4);
printSum(2,2);
printSum(1,2,3);
printSum(1, 2);
}
static void printHello(){
System.out.println("Hello, World.");
}
static void sayHiTo(String name){
System.out.println("Hello, " + name);
}
static void printSum(double x, double y){
double sum = x + y;
System.out.println("The sum of " + x + " and " + y + " is: " + sum);
}
//overloaded printSum method taking 3 params
static void printSum(double x, double y, double z){
System.out.println("Overloaded method was used");
double sum = x + y + z;
System.out.println("The sum of " + x + " and " + y + " and " + z + "is: " + sum);
}
//overloaded printSum with 2 ints
static void printSum(int x, int y){
System.out.println("Sum of two ints");
int sum = x + y;
System.out.println("The sum of " + x + " and " + y + " is: " + sum);
}
}
Code language: JavaScript (javascript)
The sum of 10.5 and 3.4 is: 13.9
Sum of two ints
The sum of 2 and 2 is: 4
Overloaded method was used
The sum of 1.0 and 2.0 and 3.0is: 6.0
Sum of two ints
The sum of 1 and 2 is: 3
Note that it called the sum of 2 ints method twice. While originally, it cast or turned the integers 2 and 2 into doubles, now that we have a specific method for ints, it used the method for ints. It still used the original printSum method for doubles when adding 10.5 and 3.4.
Return Methods
The final type of method we’ll discuss in this chapter are methods which return a particular value. Instead of declaring a method as void, we can use any variable type and return a particular variable of that type when the method is called. The keyword to return a value is return. When we return a value, the method is finished executing. In most cases, we will return a particular value at the end of the method. It is possible to return different values based on conditional logic, in which case, we may need multiple return statements for each condition.
Let’s create a method that uses two doubles as parameters and returns the sum.
static double sumOf(double x, double y){
double sum = x + y;
return sum;
}
Code language: JavaScript (javascript)
In the above code, the method’s type was declared as a double. We then added the two parameters and return the sum.
We can test this out by adding some test code to the main method.
public static void main(String[] args) {
double result = sumOf(5,5);
System.out.println("The result is: " + result);
}
Code language: JavaScript (javascript)
When executed, the program should print:
The result is: 10.0
One neat thing about having methods of particular types is that we can use them in the code anywhere we could use the original type of variable. Since this method is a double, we can use it anywhere we would usually use a double. For example, we can use the method itself in arithmetic operations.
public static void main(String[] args) {
double result = 5 + 5 + sumOf(5,5);
System.out.println("The result is: " + result);
}
Code language: JavaScript (javascript)
The result is: 20.0
We could also use it in conditional logic, or as arguments in other methods we call:
public static void main(String[] args) {
if (sumOf(5,5)==10){
System.out.println("5 + 5 = " + sumOf(5,5));
}
}
Code language: JavaScript (javascript)
5 + 5 = 10.0
We can create methods of any type we would like, as long as we’re returning that same type.
The code below checks if this is a big number and returns true or false, which for our case, will be considered anything over 99.
static boolean isBigNumber(double x){
if (x > 99){
return true;
}
else{
return false;
}
}
Code language: JavaScript (javascript)
Test in the main method…
public static void main(String[] args) {
//is 1 a big number?
System.out.println("1 is a big number: " + isBigNumber(1));
//is 1000 a big number?
System.out.println("1000 is a big number: " + isBigNumber(1000));
}
Code language: JavaScript (javascript)
1 is a big number: false
1000 is a big number: true
Chapter 6 Assignment: Biggest Number
Instructions: Create a program that asks the user to enter three numbers, which are stored as doubles. Create a method that checks the values against each other, and determines which one of the three numbers is largest. The method should use three doubles as parameters and arguments. Name the method findBiggestDouble(). Make sure the method is of type double and returns a double. Then print the result to the screen from the main method. Have the method return zero if it cannot find the biggest double, which may occur if the user enters the same number multiple times.
It should be noted that methods with a return type should always return something, even if they fail to do their expected task.
Remember to close the scanner when you’re done using it.
The program should output something like the following when complete:
Enter the first number:
50
Enter the second number:
100
Enter the third number:
39
The biggest double is: 100.0
Hints:
- The method declaration should look like this:
static double findBiggestDouble(double x, double y, double z)
- You can check for the biggest number by using multiple if/else if statements
- You can use multiple conditions or multiple nested if statements to figure out what variable is largest