The terms parameter and argument are often used synonymously. Parameters are variables that are declared in the method signature. Arguments are values that are used when the method is called. Parameters are declared in round brackets of the method signature. The parameters generally dictate how a method must be called.
In programming languages, a distinction is made between two main forms of parameter passing: call-by-value and call-by-reference. In java, the call-by-value technique is represented.
This means that parameters are passed to methods in java using a copy. Within the called function, the copy is used and changes do not affect the original value. However, the values of the instance variables of a current parameter (of the object type) can be changed.
Java has no call-by-reference! However, similar effects and memory savings can be achieved by call-by-value for objects.
class MethodParameters {
public static int add(int a, int b) {
int result;
result = a + b;
return result;
}
public static void main(String[] args) {
System.out.println(add(5, 8));
System.out.print(add(9, 21));
}
}
13
30
This is a Java program that defines a class called MethodParameters
. The class contains a public static method add(int a, int b)
that takes two integer parameters a
and b
, adds them together, and returns the result as an integer.
The main
method of the class calls the add
method twice, passing different parameters each time. The first call to add
passes the parameters 5
and 8
, and the second call to add
passes the parameters 9
and 21
.
class MethodParameters {
public static void getName(String name) {
System.out.println("Your name is: " + name);
}
public static void main(String[] args) {
getName("David");
}
}
Your name is: David
This is a Java program that defines a class called MethodParameters
. The class contains a public static method getName(String name)
that takes a single string parameter name
and prints a message to the console indicating the value of name
.
The main
method of the class calls the getName
method, passing the string "David"
as the parameter.