Consider the following Java program that passes a primitive type to function.
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 object to reference 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().
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.
Exercise: Predict the output of following Java program
This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks 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
- First strictly greater element in a sorted array in Java
- First strictly smaller element in a sorted array in Java
- How to pass an array by value in C ?
- How to pass a 2D array as a parameter in C?
- When do we pass arguments by reference or pointer?
- How to write an empty function in Python - pass statement?
- Minimum no. of iterations to pass information to all nodes in the tree
- Loops and Control Statements (continue, break and pass) in Python
- Remove elements that appear strictly less than k times
- Count Strictly Increasing Subarrays
- Convert to Strictly increasing array with minimum changes
- Find Maximum Sum Strictly Increasing Subarray
- Print all n-digit strictly increasing numbers
- Remove characters from string that appears strictly less than K times
- Generate k digit numbers with digits in strictly increasing order