Parameters and arguments

Some of the methods we have used require arguments, which are values that you provide when you invoke the method. For example, to find the sine of a number, you have to provide the number. So sin takes a double as an argument. To print a string, you have to provide the string, so println takes a String as an argument.

Some methods take more than one argument; for example, pow takes two doubles, the base and the exponent.

When you use a method, you provide arguments. When you write a method, you specify a list of parameters. A parameter is a variable that stores an argument. The parameter list indicates what arguments are required.

For example, printTwice specifies a single parameter, s, that has type String. I called it s to suggest that it is a String, but I could have given it any legal variable name.

  public static void printTwice(String s) {

When we invoke printTwice, we have to provide a single argument with type String.

  printTwice("Don't make me say this twice!");

When you invoke a method, the argument you provide are assigned to the parameters. In this example, the argument "Don't make me say this twice!" is assigned to the parameter s. This processing is called parameter passing because the value gets passed from outside the method to the inside.

An argument can be any kind of expression, so if you have a String variable, you can use it as an argument:

  String argument = "Never say never.";

The value you provide as an argument must have the same type as the parameter. For example, if you try this:


You get an error message like “cannot find symbol," which isn't very helpful. The reason is that Java is looking for a method named printTwice that can take an integer argument. Since there isn't one, it can't find such a “symbol."

System.out.println can accept any type as an argument. But that is an exception; most methods are not so accommodating.