Functions in Java

Parameters and Arguments

Information can be passed to methods as parameters. Parameters act as variables inside the method.

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

You can have as many parameters as you like.

Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.

The following example has a method that takes a String called fname as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name:

public class MyClass {
  static void myMethod(String fname) {
    System.out.println(fname + " Refsnes");
  }
​
  public static void main(String[] args) {
    myMethod("Liam");                        //Calling function myMethod() from main()
    myMethod("Jenny");
    myMethod("Anja");
  }
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

Return Values

The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method:

public class MyClass {
  static int myMethod(int x) {
    return 5 + x;
  }

Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double:

static int plusMethod(int x, int y) {
  return x + y;
}
​
static double plusMethod(double x, double y) {
  return x + y;
}
​
public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

Note: Multiple methods can have the same name as long as the number and/or type of parameters are different.