Methods : Parameters & Arguments (Part 2)
In the last tutorial we learned about Methods Declaration and Calling them.
In this tutorial , we will learn about passing an argument and parameter into methods and the difference between them.
Method Parameters
Information can be passed to methods as parameter. Parameters act as variables inside the method.
Parameters are specified after the Method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
The following example has a method getName() that takes a String called name as parameter. When the method is called, we pass along a String, which is used inside the method to print the name:
public classMyClass{ static voidgetName(Stringname) { System.out.println("Heyy I am" +name+ "."); } public static void main(String args[]) {getName("Bob");getName("Harry");getName("John"); } }
Output:-
Heyy I am Bob.
Heyy I am Harry.
Heyy I am John.
When a parameter is passed to the method, it is called an argument. So, from the example above: name is a parameter, while Bob , Harry and John are arguments.
In other words , parameters are used when declaring a method and arguments are used when calling a method.
➤Using Multiple Parameters
public classMyClass{ static voidgetInfo(Stringname, intage) { System.out.println("Hi I am" +name+ "and I am" +age+ "years old."); } public static void main(String args[]) {getInfo("Bob", 18);getInfo("Harry", 19);getInfo("John", 24); } }
Hi I am Bob and I am 18 years old.
Hi I am Harry and I am 19 years old.
Hi I am John and I am 24 years old.
➤ Return Values
public classMyClass{ static intaddOperation(intx,inty) { returnx+y; } public static void main(String args[]) { System.out.println(addOperation(5,6)); } }
11
public classMyClass{ static intaddOperation(intx, inty) { returnx+y; } public static void main(String args[]) { intz=addOperation(10, 5); System.out.println(z); } }
15
➤ Method using loops
import java.util.Scanner; public classMyClass{ static intcheckAge(intage) { returnage; } public static void main(String args[]) { Scannerscan= new Scanner(System.in); System.out.println("Enter your age:"); intage=scan.nextInt();checkAge(age); if (age< 18) { System.out.println("You are not an adult !"); } else { System.out.println("You are an adult !"); }scan.close(); } }
Enter your age:
25
You are an adult !
