5. Java support pass by value or pass by reference?

   1. Java support pass by value or pass by reference?

  • Java only support pass by value mechanism. C++ programming language support both pass by value, pass by reference, and pass by pointer.2. Pass by value and  pass by reference in C++.
  • Pass By Value

    Passing by value is passing a copy to the argument.

    • Example:
      • #include <bits/stdc++.h>
        using namespace std;
        void changeValue(int x)
        {
        	x = 2;
        }
        int main()
        {
        	int x = 0;
        	changeValue(x);
        	cout<<x;
        	return 0;
        }
        
      • Result : 0

    Consider the function changeValue(int x);x in ​​this function is another copy of x in the main function, and x is a local variable inside the function body, so changing x = 2 in the changeValue() function body has absolutely no effect on the actual value of the variable x in ​​function main. (It only changes the copy value of x inside the changeValue() function

  • Pass By Reference
    Above, we know that passing a value is passing it a copy, now passing a reference is the way we pass it an original through the address ‘&’.
  • Example with function changeValue(int &x);then the argument x here is now a reference.
  • With this transmission the data of the call can be modified by the called function.

    • Exampale:
      • #include <bits/stdc++.h>
        using namespace std;
        void changeValue(int &x) // Reference
        {
        	x = 2;
        }
        int main()
        {
        	int x = 0;
        	changeValue(x);
        	cout<<x;
        	return 0;
        }
      • As we know when declaring a variable int x = 0;then x here has been allocated memory for an address and a value, the function changeValue(int &x);then x in this function has received the address of x in the main function, so when x changes the value in the changeValue function, it leads to the value of x in the main function.
  • With pass by reference, another variable is created inside the method and it point to the same memory like original variable but we can’t point that variable into another memories during method operation.

     3.  Java use pass by value or pass by reference? 

  • In Java, when use pass a reference variable into a method, actually you pass value of that variable to the method, and inside the method, a copy of that variable is created and it’s point to the same object in heap memories.
  • I lke pass by pointer in C++, it pass the memory addess of variable into a method,  and we can point this reference variable to another memory addess during operation. Pass by reference in C++ can not do it.

Leave a Reply

Your email address will not be published. Required fields are marked *