Monday, December 30, 2024
Google search engine
HomeLanguagesJavaJava is Strictly Pass by Value!

Java is Strictly Pass by Value!

In order to understand more of how the java is processing the parameter in methods and functions, lets compare the java program with a C++ code which would make it more clear and helps you get the major difference between how the parameters are being passed to any methods or functions wrt passing parameters by value and with reference and it is the reason why Java is Strictly Pass by Value!.

Java




import java.io.*;
 
class GFG {
    // The parameters x and y in add method takes a and b.
    static int add(int x, int y)
    {
        {
            x += y;
            return x;
        }
    }
    public static void main(String[] args)
    {
        int a = 1, b = 2;
        add(a, b);
        // The addition of two values is done using the sum
        // function and the values of a does not change.
        System.out.println("After the add function a = "
                           + a);
        System.out.println("After the add function b = "
                           + b);
    }
}


C++




#include <iostream>
using namespace std;
// The parameters *x and *y in sum function takes the
// address of a and b.
int add(int* x, int* y)
{
    *x += *y;
    return *x;
}
// The parameters x and y in sum function takes a and b.
void sum(int x, int y)
{
    // Adding x and y and changing the value of x.
    x += y;
}
int main()
{
 
    int a = 1, b = 2;
    // Creating a Sum function and passing a and b as
    // parameters.
    sum(a, b);
    // Here the sum function has been called and it
    // performed an operation on x.
    cout << "The value of a after performing the add "
            "function is: "
         << a;
    cout << "\n";
    cout << "The value of b after performing the add "
            "function is: "
         << b;
    cout << "\n";
    // The addition of two values is done using the sum
    // function the values of a does not change.
 
    // Here the add function is loaded with the parameters
    // which are
    // passing with reference and the values after calling
    // the add function will change the values of original
    // values.
    add(&a, &b);
    cout << "After sum function is a = " << a;
    cout << "\n";
    cout << "After sum function is b = " << b;
    return 0;
}


Output

After the add function a = 1
After the add function b = 2

Time Complexity: O(1)
Auxiliary Space: O(1)

From the above examples of  C++ and Java programs, the parameters x and y are taking the copies of the value of a and b and performing the operation based on the copied values passed to the methods. As in all high language when ever a method or function is being parameterized they will only pass the values as copies to the methods or functions. Pointers are the efficient way of passing the parameters by reference and hence the values of the parameters are mutable as the operation being performed is on the address( memory location of variable ) rather than the value of variable.

Hence Java does not have pointers because it is a vulnerability of accessing the addresses directly and leads to major security issues and these are some of the reasons why it is considered as more secure

Consider the following Java program that passes a primitive type to function. 

Java




public class Main {
    public static void main(String[] args)
    {
        int x = 5;
        change(x);
        System.out.println(x);
    }
    public static void change(int x) { x = 10; }
}


Output

5

Output:

5

We pass an int to the function “change()” and as a result the change in the value of that integer is not reflected in the main method. Like C/C++, Java creates a copy of the variable being passed in the method and then do the manipulations. Hence the change is not reflected in the main method.

How about objects or references?

In Java, all primitives like int, char, etc are similar to C/C++, but all non-primitives (or objects of any class) are always references. So it gets tricky when we pass object references to methods. Java creates a copy of references and pass it to method, but they still point to same memory reference. Mean if set some other reference to object passed inside method, the object from calling method as well its reference will remain unaffected. The changes are not reflected back if we change the object itself to refer some other location or object If we assign reference to some other location, then changes are not reflected back in main(). 

Java




// A Java program to show that references are also passed
// by value.
class Test {
    int x;
    Test(int i) { x = i; }
    Test() { x = 0; }
}
 
class Main {
    public static void main(String[] args)
    {
        // t is a reference
        Test t = new Test(5);
 
        // Reference is passed and a copy of reference
        // is created in change()
        change(t);
 
        // Old value of t.x is printed
        System.out.println(t.x);
    }
    public static void change(Test t)
    {
        // We changed reference to refer some other location
        // now any changes made to reference are not
        // reflected back in main
        t = new Test();
 
        t.x = 10;
    }
}


Time Complexity: O(1)
Auxiliary Space: O(1)

Output

5

Output:

5

Changes are reflected back if we do not assign reference to a new location or object: If we do not change the reference to refer some other object (or memory location), we can make changes to the members and these changes are reflected back. 

Java




// A Java program to show that we can change members using
// reference if we do not change the reference itself.
class Test {
    int x;
    Test(int i) { x = i; }
    Test() { x = 0; }
}
 
class Main {
    public static void main(String[] args)
    {
        // t is a reference
        Test t = new Test(5);
 
        // Reference is passed and a copy of reference
        // is created in change()
        change(t);
 
        // New value of x is printed
        System.out.println(t.x);
    }
 
    // This change() doesn't change the reference, it only
    // changes member of object referred by reference
    public static void change(Test t) { t.x = 10; }
}


Time Complexity: O(1)
Auxiliary Space: O(1)

Output

10

Output:

10

Exercise: Predict the output of following Java program 

Java




//  Test.java
class Main {
    // swap() doesn't swap i and j
    public static void swap(Integer i, Integer j)
    {
        Integer temp = new Integer(i);
        i = j;
        j = temp;
    }
    public static void main(String[] args)
    {
        Integer i = new Integer(10);
        Integer j = new Integer(20);
        swap(i, j);
        System.out.println(" i = " + i + "
                           , j = " + j);
    }
}


Time Complexity: O(1)
Auxiliary Space: O(1)

This article is contributed by Pranjal Mathur and Lakshmi Srinivas. If you like Lazyroar and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

RELATED ARTICLES

Most Popular

Recent Comments