Please enable JavaScript to use CodeHS

Chapter 2

Using Objects

2.4 Calling a Void Method with Parameters

As you saw in the section above, you can use methods to help control and define procedures for your objects. In the last section, you looked at methods that took no input and returned no values. In this section, you are going to look at methods that take an input value, but do not return a value.

Parameters

Recall that methods are like blocks of code that do a particular thing. You can write a method that prints out “hello” when called or a method that draws a circle. But what if you want to create a method to add ten to a number? You can sketch out the method like so:

addTen() method

You would expect an addTen() method to add 10 to any number it is given. If you give it 3, the method will give us 13. Were you to give it 32, it would give us 42. This pattern can be generalized even more: if you give the method any number x, it will give us x + 10 in return. The action that the addTen() method takes is the same every time – it adds 10 – the only thing that changes is the number you give to the method. The number that you pass to the method is called a parameter.

Defining a Method with Parameters

Let’s write the addTen() method in code:

public void addTen(int x)
{
  int xPlusTen = x + 10;
  System.out.println(xPlusTen);
}
Plain text

Notice that there is an x that is being taken in and used by the method. This is the parameter. Its value will be whatever the user decides to “pass” to the method. Also, note that the x parameter can be used as a regular variable in the body of the method.

Calling a Method with Parameters

Now that the addTen() method is defined, it’s time to call the method. Let’s first add ten to the number 5:

addTen(5);
Plain text

This will result in 15 being printed to the console.

This works with variables as well. You can create a variable y that stores a number, then pass y to the addTen() method:

int y = 115;
addTen(y);
Plain text

The variable 115 is passed as an argument to the addTen() method. The method accepts 115 as the parameter, adds 10 to it, and then prints 125 to the console. Note that the argument type needs to match the parameter type.

Pass By Value

When we pass an argument to a method, it is said to be passed by value, which means a copy of that argument is made to use in the method. As a result, any change to the formal parameter will not be reflected in the actual parameters from the original calling function.

See example below and notice how the values of a and b do not change despite the fact that the parameter values were swapped in the method.

Multiple Parameters

It’s often helpful to write methods that can take in more than one parameter. For example, if you were to write a generic add() method, you would want to be able to input two numbers. To include more than one parameter, you can simply write more than one parameter, separated by a comma. The code below takes in two numbers, represented by x and y, and adds them:

public void add(int x, int y)
{
  int sum = x + y;
  System.out.println(sum);
}
Plain text

You call the method in a similar manner. If you give the function the following calls:

add(10, 90);
add(635, 1000);
int first = 72;
int second = 14;
add(first, second);
Plain text

then the program will print the following to the console:

100
1635
86
Plain text

Why Use Parameters?

Using parameters allows us to write code that is flexible and reusable. Writing a method is like telling the program to do something (for example, add two numbers or draw a rectangle on the canvas). Parameters are like giving that method specific instructions (“I want to add 3 and 7” or “I want my greeting message to say their name and my name”).

For example, if you wanted to print several greetings, you’d likely want them to contain different text depending on the person receiving the greeting. If each of these pieces of information was hard-coded into the method, you would need a separate method for each greeting!

Using parameters allows you to write one printMessage method that can be used to send many greeting messages:

public void printMessage(String to, String from, String salutation, String message)
{
  System.out.println("-------------");
  System.out.println(salutation + " " + to + ",");
  System.out.println(message);
  System.out.println("Best regards,");
  System.out.println(from);
  System.out.println("-------------");
}
Plain text

If Karel wants to send a birthday message to Bill Gates and a Halloween card to Steve Wozniak, Karel could write:

printMessage("Bill Gates", "Karel", "Howdy", "Wishing you a happy birthday!");
String halloweenMessage = "Hope you have a spooky Halloween!";
printMessage("Steve Wozniak", "Karel", "Hi", halloweenMessage);
Plain text

This would print two letters to the console:

-------------
Howdy Bill Gates,
Wishing you a happy birthday!
Best regards,
Karel
-------------
-------------
Hi Steve Wozniak,
Hope you have a spooky Halloween!
Best regards,
Karel
-------------
Plain text

Parameter Order

It’s very important to pass arguments to methods in the proper order. Using the printMessage example above, you may know that Karel is the name of the person sending the message and that you want it to start with “Howdy”, but the computer does not know this information. The way that the computer finds out which argument goes to which parameter is by the order in which your code passes the arguments into the method.

For example, if you wrote:

printMessage("Howdy", "Karel", "Wishing you a happy birthday!", "Bill Gates");
Plain text

you would end up with a mixed-up message:

-------------
Wishing you a happy birthday! Howdy,
Bill Gates
Best regards,
Karel
-------------
Plain text

As you can see, order matters when you are using parameters.

Calculator

Method Overload

As you saw with constructors, you can also overload methods. Recall that a method signature consists of the method name and the ordered list of parameter types. You can overload a method by giving the method the same name as another method, but a different signature by having a different ordered list.

Here is an example of a proper overload:

public int add(int a, int b) {  }
public int add(int a, int b, int c) {  }
Plain text

Notice in the example above how one method takes two integers as an input and the other takes 3 integers. It is important to note that the variable names do not make a difference, it is only the type and order of the parameters. Given a method signature like this:

public int add(int x, int y, int z) {  }
Plain text

The above would not overload the methods above since there is already a method that takes three integers. Changing the variable names doesn’t impact whether a method is overloaded.

Moving a Point

Rectangle

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    Suppose there is a class called Athlete. One of the methods is given below. It sets the instance variable isAllStar to the parameter value.

    public void setAllStarStatus(boolean status)
    {
        isAllStar = status;
    }
    Java

    Using the Athlete object called karel, which of the following is the correct way to set karel’s all-star status to false?

Exercise: More Operations

Let’s look at a calculator class. We have a calculator class that allows us to add, subtract, multiply, and divide doubles.

In the main method, ask for two doubles. Then print the sum, difference, product, and quotient.

For example, your output should look like this
(you can call nextDouble twice in a row to get two numbers)

Enter two doubles
3.4
1.6
3.4 + 1.6 = 5.0
3.4 - 1.6 = 1.7999999999999998
3.4 * 1.6 = 5.44
3.4 / 1.6 = 2.125
Plain text

Note: Wondering why you get really long decimal numbers sometimes? That’s because the computer cannot actually represent all decimal numbers accurately. The approximations cause rounding errors when you use the numbers in calculations. This is called a “floating point error”.