Parameter passing in Java


In the previous tutorial, we have known that the basic method of passing parameters in java is call-by-value. It means that if the method modifies the values of parameter, its modification will not remain after the scope of method is over. That is such modification inside the method does not affect original passing arguments.

When a method needs input, the definition of a method contains the number of formal parameters and call to a method contains actual arguments. When we call a method, the actual arguments in method calls have to be passed to the formal parameters of method definition. This process is called passing parameters in java or simply called passing arguments to methods.

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 as follows:
1. Passing parameters of simple or primitive data type
2. Passing parameters of reference data type
Parameter passing in java

Passing parameters of Primitive Data type


Java passes parameters of primitive data types (like int, char, float, double) and String by passed-by-value. 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.

Let's take an example program where we will declare an instance method m1() and static method m2() in a class Simple. In instance method m1(), we will pass primitive values (int and char) and in the static method m2(), String and double argument will pass by value. So, let's see the following source code. 
Program source code 1:
    package methodPrograms; 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 an object of the class to call the instance method. Simple s = new Simple(); // Call m1 method using reference variable s and pass two values (int and char). s.m1(23, 'D'); // Call the static method using class name and pass two values (String and double). Simple.m2("Shubh", 15.5); } }
    Output: m1 method is calling 23 D m2 method is calling Shubh 15.5
Let's understand another example where we will change the value of the parameter inside the method but it will not affect the original value after calling.

Program source code 2:
    package methodPrograms; public class PassPrimitiveByValue { // Declare an instance variable and initialize a value 5. int x = 5; void m1() { // Calling passmethod() with x as argument. passmethod(x); System.out.println("After calling passmethod, x = " +x); } // Changing 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 passmethod, x = 5
In the preceding code, when we called m1() method by using object reference variable pp, it calls passmethod() method by passing a value 5 as an argument. The control of execution is immediately transferred to passmethod(). Within passmethod() method, we changed the value of parameter.

After the complete execution of passmethod(), the control of execution is transferred back to m1() method. The value of x will be print 5 on the console, not 10. Thus, the changed value did not affect the original value and the original parameter value remains intact.

Passing parameters of Reference Data type


Passing parameters of reference data type mean passing the reference of the object by value. When we call a method with passing the reference of an 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.

For example:
            void m1( Emp e ); 
where,
       e is the object reference variable and Emp is the name of a class.

Note: Java passes the arguments by value for both primitives and objects. Java never passes the object itself.
Let us understand the following example program based on this concept.

Passing class object as parameters to method call in Java


In the above program, we passed the integer, double, string, char values to the parameters of methods but in a real-time project of the company, we do not pass 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. So, let's understand the above scenario by the following source code.

Program source code 3:
    package methodPrograms; class Student { . . . . . . . . . . } class Library { . . . . . . . . . . } class Admin { . . . . . . . . . . } class Employee { . . . . . . . . . . } class School { // Declare an 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 an object of the class school. School sc = new School(); // Now, create objects of classes Student and Library. Student s = new Student(); // (1) Library l = new Library(); // (2) // Pass the object reference variables as an 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 will same work . // 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 between ep and ep1. OR, we can also write as // School.m2(new Admin(), new Employee()); } }
    Output: m1 is calling m2 is calling

Can we have two methods with the same name in class?


Let's create a program where we will declare two methods with the same method name in a class and check what kind of error comes?
Program source code 4:
    package methodPrograms; public 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 an error: method m1() is already defined in class SameMethodName. Duplicate methods are not allowed due to the same method signature. If you try to run the above code, you will get the output "Hello Java".

Can we have two methods having the same name with different parameters?


Yes, we can have two methods having the same name with different parameters in a class. This technique is called method overloading in java. Let's take a simple example program where we will define two methods having the same name with different parameters.
Program source code 5:
    package methodPrograms; public 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
As you can see in the preceding example program, both m1() method is valid because the method signature is different due to different parameters. Different signature is valid but the same signature is not valid in java.

Can a method be defined inside a method in Java?


Declaring a method inside another method is called inner method in java but in the entire Java, the inner method concept are not allowed. 
Note: Java supports the inner class concept but does not support the inner method concept.

Let's take an example program where we will define a method inside a method in a class.
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 code will give an error because java does not support inner method and it is an invalid program.

How to call a method in Java from another class?


To call a method in Java from another class is very simple. We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable. Let's understand it 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 another class SimpleText.
    public class SimpleTest { public static void main(String[] args) { // Create the object of the class SimpleExp. SimpleExp se = new SimpleExp(); // Now, call m1() method 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.
In the above program, we are calling m1() method from another class SimpleTest but m1() is calling m2(). So, the control of execution is immediately transferred to m2(). Now, m2() is calling m3() with an integer argument. 

So, the control of execution is again transferred to m3() and the SOP statement will be executed. After complete execution of m3() method, the control of execution will go to m2() and executes the SOP statement. Now, the control of execution will go to m1() and execute the statement.

Let's take important example programs that can be asked in any Java technical test or interview.
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 coding, both instance variables ( a, b ) and local variables ( x, y ) in parameters are the same names. So, to find out output is very easy but if both are different then What will be output in this case? Let's see it.

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 program, both local and instance variables are having the same name, So in this case, the first priority will go to local variables, not instance variables. Therefore, the output will be 100, 100.

Final words
Hope that this tutorial has covered almost all important points related to passing parameters mechanism in java. I hope that you will have understood how to call a method with parameters in java.
Thanks for reading!
Next ➤ Return type in Java ⏪ Prev Next ⏩