Java Method Parameters

Parameters let you pass information into a method so it can work with different values each time you call it. Instead of a method that always does the exact same thing, parameters make a method flexible and general-purpose.

Parameters and arguments

A parameter is a variable listed inside the parentheses when you define a method. An argument is the actual value you hand to the method when you call it. The words are often used loosely, but the difference is simple: parameters are the placeholders, arguments are the real values that fill them.

A method with one parameter

public class Main {
  // name is a parameter
  static void greet(String name) {
    System.out.println("Hello, " + name + "!");
  }

  public static void main(String[] args) {
    greet("Asha");   // "Asha" is an argument
    greet("Ravi");   // "Ravi" is an argument
  }
}

// Output:
// Hello, Asha!
// Hello, Ravi!

The same method now produces different output depending on what you pass in. That is the power of parameters: one definition, many results.

Multiple parameters

A method can take as many parameters as you need. Separate them with commas, and give each one a type and a name. When you call the method, the arguments must appear in the same order as the parameters.

Two parameters of different types

public class Main {
  static void describe(String product, double price) {
    System.out.println(product + " costs $" + price);
  }

  public static void main(String[] args) {
    describe("Notebook", 4.5);
    describe("Backpack", 29.99);
  }
}

// Output:
// Notebook costs $4.5
// Backpack costs $29.99
Note: The number and types of arguments must match the parameters. Calling describe("Pen") or describe(4.5, "Pen") would cause a compile error, because the arguments do not line up with the declared parameters.

Parameters are passed by value

Java passes arguments by value, which means the method receives a copy of the value. For primitive types like int, changing the parameter inside the method does not affect the original variable outside it.

The original variable is unchanged

public class Main {
  static void addTen(int number) {
    number = number + 10; // changes only the local copy
  }

  public static void main(String[] args) {
    int score = 5;
    addTen(score);
    System.out.println(score); // still 5
  }
}

// Output:
// 5
TermWhere it appearsExample
ParameterIn the method definitionString name
ArgumentIn the method call"Asha"
Parameter listInside the parentheses(String product, double price)
Note: For objects and arrays, the copied value is a reference, so the method can change the contents of the object. But it still cannot make the original variable point to a brand new object. This subtle point becomes clearer once you study objects.