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 class
MyClass
{ static void
getName
(String
name
) { 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 class
MyClass
{ static void
getInfo
(String
name
, int
age
) { 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 class
MyClass
{ static int
addOperation
(int
x
,int
y
) { return
x+y
; } public static void main(String args[]) { System.out.println(
addOperation
(5,6)); } }
11
public class
MyClass
{ static int
addOperation
(int
x
, int
y
) { return
x
+
y
; } public static void main(String args[]) { int
z
=
addOperation
(10, 5); System.out.println(
z
); } }
15
➤ Method using loops
import java.util.Scanner; public class
MyClass
{ static int
checkAge
(int
age
) { return
age
; } public static void main(String args[]) { Scanner
scan
= new Scanner(System.in); System.out.println(
"Enter your age:
"); int
age
=
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 !