12.5: Parameters and Arguments
- Page ID
- 15232
Some of the methods we have used require arguments, which are the values 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 display a message, you have to provide the message, so println
takes a String
.
When you use a method, you provide the arguments. When you write a method, you name the parameters. The parameter list indicates what arguments are required. The following class shows an example:
public class PrintTwice { public static void printTwice(String s) { System.out.println(s); System.out.println(s); } public static void main(String[] args) { printTwice("Don't make me say this twice!"); } }
printTwice
has a parameter named s
with type String
. When we invoke printTwice
, we have to provide an argument with type String
.
Before the method executes, the argument gets assigned to the parameter. In this example, the argument "Don't make me say this twice!"
gets assigned to the parameter s
.
This process 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."; printTwice(argument);
The value you provide as an argument must have the same type as the parameter. For example, if you try:
printTwice(17); // syntax error
You will get an error message like this:
File: Test.java [line: 10] Error: method printTwice in class Test cannot be applied to given types; required: java.lang.String found: int reason: actual argument int cannot be converted to java.lang.String by method invocation conversion
Sometimes Java can convert an argument from one type to another automatically. For example, Math.sqrt
requires a double
, but if you invoke Math.sqrt(25)
, the integer value 25
is automatically converted to the floating-point value 25.0
. But in the case of printTwice
, Java can’t (or won’t) convert the integer 17
to a String
.
Parameters and other variables only exist inside their own methods. Inside main
, there is no such thing as s
. If you try to use it there, you’ll get a compiler error. Similarly, inside printTwice
there is no such thing as argument
. That variable belongs to main
.
Because variables only exist inside the methods where they are defined, they are often called local variables.