Scientech Easy How to call a method with Parameters in Java? | Scientech Easy

Monday, August 27, 2018

How to call a method with Parameters in Java?


Method Argument and Parameter in Java


Definition
Argument: What is passed "to" a called method is known as an argument?  In other words, Arguments are the actual values that are passed in a method when that method is called. Sometimes, an argument is also called the actual parameter.
For example:
  add(5,7);
  sum(35, 47);
The values 5 and 7 are the arguments with which a method will be called.
Parameter: Parameter is the list of variables in a method declaration. In other words, The "type" of value or data that a method can receive is known as a parameter. It is often called a formal parameter.
For example:
 1.  public int add(int a, int b){
      return (a+b);
   } 
The method add has two parameters, named a and b with data type integer. It adds the values passed in the parameters and returns the result to method caller.
 2.  void sum(int x, int y)
The method sum has two parameters x and y.
While passing the argument values to the parameters, the order of parameters and number of parameters are very important. These must be in the same order as their respective parameters declared in the method declaration.  

Parameter types

We can use any data type such as primitive data types including int, float, double, char, String, and object reference variables for a parameter of a method and constructor. We will see in detail in example programs one by one.
There is no standard limit to specify the number of parameters in a method declaration but you should limit the number of parameters almost 6 to 7 and any more will have a negative effect on the readability of your code.

How to call a method with Parameters in Java?

There are two most common ways by which we can call a method with parameters in Java. They are:
Learn how to call a method with parameters in Java, Method Argument, and Parameter, Parameters Types, Passing primitive data types arguments, Passing Reference data type arguments, Inner method.
Ways to call a method with Parameters in Java

1. Passing Primitive data type arguments: 
When a method is called with passing values to the parameter list of a method, These values are copied into the small portion of memory and a copy of each value is passed to the parameters of the called method. When these values are used inside the method either for "read or write operations", we are actually using the copy of these values, not the original values which are unaffected by the operation inside the method. That is, The values of the parameters can be changed only within the scope of the method but such changes cannot affect the original passing values. When the method returns, the parameters are gone and any changes to them are lost. This whole process is called Pass by value.  
Let's see a simple example.
Program source code 1: In this example, we are passing primitive values such as int and char into instance method m1() and in the static method m2(), String and double arguments are passing by value

    package basicExample; public class Simple { // Declare instance method with two parameters. Method parameters are always local variables. // Variables declared inside the method are local variables. void m1(int a, char ch){ System.out.println("m1 method is calling"); System.out.println(a); System.out.println(ch); } // Declare static method with two parameters. static void m2(String str, double d){ System.out.println("m2 method is calling"); System.out.println(str); System.out.println(d); } public static void main(String[] args) { // Create the object of the class to call the instance method. Simple s=new Simple(); // Call m1 method using reference variable s and pass the two values. s.m1(23, 'D'); // Call the static method using class name and pass the two values Simple.m2("Shubh", 15.5); } }
    Output: 23 D m2 method is calling Shubh 15.5
Program source code 2: In this example, we will change the value of the parameter inside the method but it will not affect the original value after calling.
    package basicexample; public class PassPrimitiveByValue { // Declaration of instance variable with value. int x=5; void m1(){ // Call the passmethod with x as argument. passmethod(x); System.out.println("After calling the passmethod, x=" +x); } //Change the parameter in the passmethod. static void passmethod(int y){ y=10; } public static void main(String[] args) { PassPrimitiveByValue pp=new PassPrimitiveByValue(); pp.m1(); } }
    Output: After calling the passmethod, x=5
2. Passing Reference data type arguments: 
Passing Reference data type arguments means passing the reference of the object by value. When we call a method with passing the reference of the object by value, Java does not copy the object into the memory. Actually, it copies the reference of the object into the memory and passes the copy to the parameters of the called method. If we change the reference of the object then the original reference does not get changed because this reference is not original. it's a copy.
Example:
   void m1(Emp e); where e is the object reference variable and Emp is the name of a class.
Note: Always remember, Java passes the arguments by value for both primitives and object. Java never passes the object itself.
Let's see an example to understand this concept.

Program source code 3: In the above program, we passed the integer, double, string, char values to the parameters but in a real-time project in the company, we do not pass the int, float or double values to the parameters. We pass the reference of the object as a value to the parameters.

Suppose in a real-time project, we are developing a school application in which there are five modules such as Student, Library, Admin, Employee, and School. We will create a class for each module and will pass the object of the class to call the method m1() and m2() in the school class.
    class Student { - - - - - - - - - - } class Library { - - - - - -- - - - } class Admin { - - - - - -- - - } class Employee { - - - - - - - } class School { // Declare the instance method with two objects of Student and Library classes as parameters. void m1(Student s, Library l){ // s and l are object reference variables. System.out.println("m1 is calling."); } Similarly, public static void m2(Admin a, Employee ep){ System.out.println("m2 is calling"); } public static void main(String[] args){ // First create the object of the class school. School sc=new School(); // Now create the object of the classes Student and Library. Student s=new Student(); // (1) Library l=new Library(); // (2) // Pass the object reference variables as argument value to the method m1 for calling m1(). sc.m1(s,l); // (3) Above three lines of code, can be replaced by a single line of code. Both are the same working. sc.m1(new Student(), new Library()); Similarly, Admin a=new Admin(); Employee ep1=new Employee(); School.m2(a,ep1); // We can pass different Employee type reference variable. Reference Variable name is not important but Employee type is important. So don't confuse in ep and ep1. OR School.m2(new Admin(), new Employee());
    Output: m1 is calling m2 is calling
Program source code 4: In this program, we are declaring two methods with the same name. So in this case, What will be output? Let's check.
    class SameMethodName { void m1(){ System.out.println(" Hello Java "); } void m1() { System.out.println(" Welcome to Java world "); } public static void main(String[] args){ SameMethodName obj=new SameMethodName(); obj.m1(); } }
The above program will give error: method m1() is already defined in class SameMethodName. 
Always Remember: Duplicate methods are not allowed due to the same method signature.

Program source code 5:
    class SameMethodName { void m1(){ System.out.println(" Hello Java "); } void m1(int a) { System.out.println(" Welcome to Java world "); } public static void main(String[] args){ SameMethodName obj=new SameMethodName(); obj.m1(); obj.m1(5); } }
    Output: Hello Java Welcome to Java world
In this program, both m1() method is valid because the method signature is different due to different parameters. 
Always Remember: Different signature is valid but the same signature is not valid.

Can a method be defined inside a method in Java?

Inner method
Declaring a method inside another method is called Inner method but entire Java, inner method concept are not allowed. 
Always Remember: Java supports the inner class concept but Java does not support inner method concept.
Let's take an example program.
Program source code 6:
    public class InnerMethod { void m1(){ System.out.println(" Hello Java "); // Declaration of Inner method. void m2() { System.out.println(" Hi Java "); } } public static void main(String[] args){ InnerMethod obj=new InnerMethod(); obj.m1(); } }
The above program will give error as output because java does not support inner method and it is invalid program.

How to call a method in Java from another class?

To call a method in Java from another class is very simple. Let's understand with an example program.
Program source code 7:
    package methodCalling; public class SimpleExp { void m1(){ m2(); System.out.println("Java is developed by Sun Microsystem."); } void m2(){ m3(5); System.out.println("Java is a popular programming language"); } void m3(int x){ System.out.println("Welcome to online Java tutorial "); } }
Now create the another class.
    package methodCalling; public class SimpleTest { public static void main(String[] args) { // Create the object of the class SimpleExp. SimpleExp se=new SimpleExp(); // Now call the m1() using object reference variable se. se.m1(); } }
    Output: Welcome to online Java tutorial Java is a popular programming language Java is developed by Sun MicroSystem.
Execution process: We are calling m1() from another class SimpleTest but m1() is calling m2(). So the control of execution is transferred to m2(). Now m2() is calling m3() with an integer argument. So the control of execution again transferred to m3() and SOP statement will be executed. After SOP execution, it will go to m2() and execute SOP statement. Now the control of execution will go to m1() and execute the statement. 
Thus, we can call a method from another class. Just create the object of that class inside another the class and call the method using object reference variable.

Program source code 8:
    public class AddTest { // Instance variable int x=10; int y=20; void add(int a, int b){ // Here a and b are local variables. System.out.println(x+y); System.out.println(a+b); } public static void main(String[] args) { AddTest ad=new AddTest(); ad.add(50, 50); } }
    Output: 30 100
In the above program 8, Both Instance variables and local variables are having the same name as x,y and a,b. So to find out output is very easy but if both are different then What will be output in this case? See below example

Program source code 9:
    public class AddTest { // Instance variable int x=10; int y=20; void add(int x, int y){ // local variables System.out.println(x+y); System.out.println(x+y); } public static void main(String[] args) { AddTest ad=new AddTest(); ad.add(50, 50); } }
    Output: 100 100
In this example, both local and instance variables are having the same name, So in this case, First priority will go to local variables, not instance variables. Therefore the output is 100, 100. 
Final word:
I hope that this article has covered almost all practical example and programs of the method concept. In the next article, we will see the example and programs related to return type.
All the above programs are very important, especially for beginners. 



Next ➝ Return type in Java

Hot Post

Java Collections Framework | Need & Advantages