This guide will explain the method to pass arguments to methods along with possible examples.
How to Pass Arguments to Methods in Java?
In Java, passing arguments to methods refers to passing data or values as parameters to a method so that the method can perform operations using those values.
The syntax for passing arguments to methods in Java is as follows:
Here, “methodName” refers to the name of the method that is being called, and “argument1”, “argument2”, …, “argumentN” are the values or data that are passed to the method.
Note: The parameters that can be passed to a method are unlimited, if the method signature (i.e., the number, type, and order of the arguments) matches the method definition.
Example 1
Here is an example of a method that takes two arguments:
public static void main(String[] args) {
int result = sum(5, 7);
System.out.println("The s um is " + result);
}
public static int sum(int num1, int num2) {
return num1 + num2;
}
}
In this example,
- Define a method called sum() that takes two integer arguments “num1” and “num2”.
- Then, call the sum method from the main method and pass it to two integer values 5 and 7.
- The “sum()” method performs its task and returns the result.
Output
The method used arguments to perform its task and return a result “12”.
Note: If the argument types do not match the parameter types, you will get a compilation error.
Example 2
Here is an example of a method that takes a string argument:
public static void main(String[] args) {
String message = "Hello, World!";
printMessage(message);
}
public static void printMessage(String message) {
System.out.println(message);
}
}
In this example,
- Define a method called printMessage that takes a single-string argument message. The method prints the value to the console.
- Then, call the “printMessage” method from the main method and pass it a string value “Hello, World!”.
- The “printMessage” method performs its task and prints the value to the console.
Output
Finally, print the result value “Hello, World!” to the console window.
Conclusion
Passing arguments to methods in Java allows developers to pass data or values as parameters to a method. This is a fundamental aspect of Java programming, as it enables the method to perform operations using those values. The syntax for passing arguments to methods in Java is straightforward and easy to use, and the number of arguments that can be passed to a method is unlimited.