Method parameters

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.

Code Explanation

LineDescription
2Function header of the add() function with input parameters a and b of type integer. Static methods can be called via a class and it is not necessary to create an object each time. A public method can also be called outside the class in which it was declared. The return value of the method is of type integer
3Create variable named result of type integer
4Result is assigned the sum of a and b
5Returns the variable result
8main() function of type void
9Calls the add() function with the parameters 5 and 8 in an output stream and thus outputs the sum of the two numbers
10Calls the add() function with the parameters 9 and 21 in an output stream and thus outputs the sum of the two numbers
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));
	}
}
Output
13
30

Another Example

Code Explanation

LineDescription
2Method header of the getName() method with input parameter name of type String. The return value of the method is of type void
3Outputs the name in a string
7Calls the method with the string parameter “David”
class MethodParameters {
	public static void getName(String name) {
		System.out.println("Your name is: " + name);
	}

	public static void main(String[] args) {
		getName("David");
	}
}
Output
Your name is: David