In this Java article we want to learn about Java Method Parameters, so Java is an object oriented programming language and that is widely used for developing different types of software applications, from web applications to mobile applications. one of the important concept in Java programming language is Java method, Methods in Java can take zero or more parameters, which are variables that are passed to the method for it to use during its execution.
So syntax of method parameters in Java is like this:
1 2 3 |
public void methodName(parameter1, parameter2, ...) { // Method body } |
In here parameter1, parameter2 and so on represents the variables that are passed to the method. these variables can be of any data type, including primitive types such as int, float and boolean or object types such as String and ArrayList. methodName represents the name of the method, and the public keyword represents the access modifier. void keyword indicates that the method does not return any value.
There are two types of method parameters in Java, now let’s talk about the types.
1. Value Parameters
Value parameters are the most common type of method parameters in Java. they are used to pass values to a method, and after that you can use that within the method body.
1 2 3 |
public void method(int x, float y, String s) { // Method body } |
In the above example, int x, float y and String s are value parameters. values passed to these parameters are stored in separate memory locations and can be accessed within the method body.
2. Reference Parameters
Reference parameters are used to pass references to objects of a method. this means that the parameter is not a copy of the object , but it is a reference to the memory location where the object is stored.
1 2 3 |
public void method(ArrayList<String> list) { // Method body } |
In the above example ArrayList<String> list is a reference parameter. parameter list holds a reference to an object of type ArrayList<String>. any changes made to the object within the method body will also affect the object outside the method.
Parameters can be passed to a method in Java by specifying their values when calling the method. the values that are passed must match the data type of the parameters specified in the method signature.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Example { public static void main(String[] args) { Example ex = new Example(); int x = 5; float y = 3.14f; String s = "Hello"; ex.method(x, y, s); } public void method(int x, float y, String s) { // Method body } } |
In the above example we have created an instance of the Example class and pass three values to the method() method using ex.method(x, y, s) statement.
Learn More