I am very confused about this thing in java about pass by value and pass by reference , I know that all the primitive data types are passed by value and objects are passed by reference , but can anyone please explain it with a bit of example please?
Pass by value, by reference
Started by ahmed, Oct 27 2009 01:05 AM
6 replies to this topic
#1
Posted 27 October 2009 - 01:05 AM
|
|
|
#2
Posted 27 October 2009 - 01:19 AM
Cat firstCat = new Cat()
YourMethod(firstCat); // Cat's reference is being passed here
Cat secondCat = firstCat; // Cat's reference is being passed here
int i = 5;
anotherMethod(i); // primitive data type is passed by value
int e = i; // also passed by value.
If you pass something by reference then you are just passing the address, and object stays as one, so you can't change it without changing it for others.
If you pass value, it will be copied, and results are independent from each other.
#3
Posted 27 October 2009 - 01:21 AM
I know about the concepts but just messed up cause I am studying Java course in my university so sucks to switch from C++ to Java in the beginning ,So what about the double data type in java , it's passed by value others are passed by reference , why?
Solved the problem understood it ;) thanks anyways
Solved the problem understood it ;) thanks anyways
Edited by ahmed, 27 October 2009 - 02:06 AM.
#4
Posted 27 October 2009 - 02:57 AM
When you pass a primitive variable, it is passed by copy. So modifying the copy in the method will not change the variable outside the method.
When you pass an object, it is passed by reference. Thus if you modify the object in the method, it will be updated in the method that called it as well.
When you pass an object, it is passed by reference. Thus if you modify the object in the method, it will be updated in the method that called it as well.
#5
Posted 27 October 2009 - 04:22 AM
one question , if i want to pass a primitive variable by reference how can I do it? I can't seem to do it with & operator cause it's not in Java i think
#6
Posted 27 October 2009 - 10:43 AM
That would require pure pointers to memory, but java doesn't allow that for primitives(as well as i know...)
The reason you can't pass primitives by reference, is that you don't need that...ever. Java has static variables for that, and in case you need to change the original primitive, you can always return the value from a function..
The reason you can't pass primitives by reference, is that you don't need that...ever. Java has static variables for that, and in case you need to change the original primitive, you can always return the value from a function..
#7
Posted 27 October 2009 - 04:25 PM
Also, Java has all of the primitives as objects, so if you really need to pass primitives by reference, simply box them into an object and pass them into the function. :)
Wow I changed my sig!


Sign In
Create Account


Back to top









