AI Hints
Home›Java Tutorial›Defining Methods, Parameters and Return Values
Java · Lesson 56 of 120

Parameters

Give a method some input.

⏱ 2 min read▶ Video at 1:10:15🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Parameters let you pass values into a method. The same method can then work with different values each time.

  • Pass values in
  • Same method
  • Different values

Passing values in

Greet now has a parameter, a String called name. Inside the method, name is a normal variable. When we call greet with Ana, name holds Ana. A method can have several parameters, separated by commas. Run it. Two greetings, and two prices.

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

    static void showPrice(String item, double price) {
        System.out.printf("%s costs %.2f%n", item, price);
    }

    public static void main(String[] args) {
        greet("Ana");
        greet("Ben");
        showPrice("Tea", 2.5);
        showPrice("Cake", 3.75);
    }
}
Output
Hello, Ana!
Hello, Ben!
Tea costs 2.50
Cake costs 3.75

Order and types matter

The values you pass are called arguments. They must match the parameters, in number, order, and type. Here, we passed them the wrong way round. Run it. Java refuses to compile.

Main.javajava
public class Main {
    static void showPrice(String item, double price) {
        System.out.println(item + " costs " + price);
    }

    public static void main(String[] args) {
        showPrice(2.5, "Tea");
    }
}
Output
Main.java:7: error: incompatible types: double cannot be converted to String
        showPrice(2.5, "Tea");
                  ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full
output
1 error
error: compilation failed

Parameters and arguments

Parameters are the names in the method's definition. Arguments are the actual values in a call. Java matches them by position. And each parameter needs its own type.

keyvalue
ParameterString name, in the definition
Argument"Ana", in the call
Matchedby position
Each needsits own type

Summary

Parameters are inputs to a method. Arguments are the values you pass, in the same order and types. Next, getting a value back.

Key takeaways
  • name(Type p)
  • Call with arguments
  • Order and type matter
Next up: Return Values — get an answer back