Skip to content

Method Parameters

Estimated time to read: 2 minutes

Overview

  • Method parameters allow data to be passed into a method.
  • Multiple method parameters are separated by a comma.

Overloading Methods

Java will accept methods with the same name as long as they have different signatures. This is known as overloading methods.

Return values are not considered when determining the uniqueness of method signatures.

Overloaded methods can also vary in accessibility.

Example: Overloading Methods

package io.entityfour;

public class Car {

 public void setTirePressures(int tire1, int tire2, int tire3, int tire4){
  // Method body goes here
 }

 public void setTirePressures(int tires){
  // Method body goes here
 }
}

The example above has two methods with the same name, but with different parameter inputs. This means that different code can be run depending on the parameters given.

Variable Argument Methods

Variable length arguments give additional flexibility by allowing the definition of methods that accept a varied number of arguments, however, all arguments must be of the same type.

An elipsis (...) is used within a method signature to denote a variable number of ints. This is known as varargs.

For example;

public void myExampleMethod(int ... v){
 // Method body goes here
}

Prior to the addition of varargs

public void setTirePressures(int[] pressures){

}

An array of a type would have to be passed in to the method. Instead of being able to pass this values in normally, you would have to create an array when calling the object. For example:

mach5.setTirePressures(new int[] (32,32,40,50));

After the addition of varargs

public void setTirePressures(int ... pressures){

}
mach5.setTirePressures(32,32,40,50)

Varargs automatically creates an int array in this instance. A variable number of arguments can be passed into the method. x