Ok bit of an odd question. I have the following code, which just creates a simple java object called DumObj and sets a string value using a setter method. Then a few methods are called from a TestBed class using the DumObj as a parameter.
I initially thought that calling TestBed.updateId(DumObj) would not affect my DumObj, and the initial value of ID that was set to "apple" would stay the same. (Because of the whole pass-by-value thing)
However the value of ID was set to the updated value of "orange". Ok I thought, that's weird, so I wrote another method, TestBed.setToNull(DumObj). This method just sets DumObj to null, so when I call the getId() method I was expecting to get a null pointer exception.
However the output I got was the value of ID still set to "orange".
Code is as follows :
public static void main(String[] args)
{
TestBed test = new TestBed();
DumObj one = new DumObj();
one.setId("apple");
System.out.println("Id : " + one.getId());
test.updateId(one);
System.out.println("Id : " + one.getId());
test.setToNull(one);
System.out.println("Id : " + one.getId());
}
public void updateId(DumObj two)
{
two.setId("orange");
}
public void setToNull(DumObj two)
{
two = null;
}
Output is as follows :
Id : apple
Id : orange
Id : orange
It's probably something really simple I'm overlooking, but can someone explain this behaviour to me? Is Java not pass-by-value?
When you write
DumObj one = new DumObj();
it's important to realise that one is not a DumObj - it's a reference to DumObj, and references are passed by value.
So you're always passing by value, and you can change the passed reference (so your passed reference now points to a different object). However, your object itself could be mutable, so this:
one.setValue(123);
will change the referenced object. When you call this:
public void setToNull(DumObj two)
{
two = null;
}
you're changing the passed reference (remember - it's been passed by value and is local to the method!) and so your original object and original reference are not affected.
When you do:
two = null;
You are only setting the two variable reference to null. The object that it was pointing to still exists, and is referenced by one.
On the other hand, when you do:
two.setId("orange");
You are modifying the object that is referenced by both one and two.
Java is kind-of "pass reference by value" for objects. So in setToNull(DumObj two), two is a reference to an object. If you say two = null;, that now makes two a reference to not an object; it doesn't change the object. If, on the other hand, you do something like two.setId("blue"), you are changing the object that two references.
When you call updateId the new reference variable two and old reference variable one both referring to same object in heap so changing one gets reflected in other reference variable.
now when you call setToNull again new reference variable two and old reference variable one both referring to same object.But here when you do two = null only reference variable two point to null object. but reference variable one still pointing to same object.When you do two==null ,you are not changing any value in object referred by it but instead you are referring reference variable to null.
In case in setToNull method you write two=new DumObj(); then a new object in heap will be created and two will point to this new object .and then for ex if you write
two.setId("banana");
and in your main code if you write one.getId() inside syso then it will print orange not banana.
hope i helped.
Yes, Java is pass by value. But your variables are really pointers to the object allocated on the heap. So what its passed by value is the pointer, not the object.
In your examples:
public void updateId(DumObj two)
{
two.setId("orange");
}
The first passes the variable (pointer) by value, that is, updateId() recieves a copy of the pointer. But what you are doing here is to modify the object pointed by the pointer. So the object was modified when you return to the caller function.
public void setToNull(DumObj two)
{
two = null;
}
In the second case, you are assigning null to a copy of the original pointer, not the original pointer itself, so that function call has no effect at all in the origial variable.
Related
I read in this question that Java is always pass-by-value. And so even references are passed by value.
I don't understand what this means, can somebody clarify this for me please?
Given this
Object ref = new Object();
ref is actually storing a value, some address to an object. Let's say 1234.
When you pass ref around
public void method(Object passed) {...}
...
method(ref);
Java actually copies the value of the reference and assigns it to the parameter. So, passed will also have the value 1234.
Similarly, if you had
Object otherRef = ref;
the value 1234 would be copied and assigned to otherRef.
If you then re-assign otherRef, like
otherRef = new Object();
that would assign a new value to otherRef, but ref would still have the same value as before. That's what pass by value is.
When you call a method
ref.toString();
Java uses the value of the reference to find the referenced object and invoke the method. This is called dereferencing.
You might want to go through the JPDA javadoc, starting with StackFrame. Go through the fields and types and you'll start to understand how everything is mapped. For example, it has a getValues(..) method which returns a Map<LocalVariable, Value>. That should tell you that a variable doesn't actually store anything. Instead, it is mapped to a value, where that value may be all sorts of things.
int a = 5;
public void foo(int num) {
num = num + 5;
System.out.println(num);
}
foo(a);
System.out.println(a);
In the above code, a is passed into foo() by value. That means that a new variable is created with the scope of foo() that has the same initial value as a. When the value of num is changed, the value of a is not changed. The first println() will print a 10, the second will print a 5. In c++ you could pass a in by reference, which means that the value of a would be changed too.
I can try, in some other languages you have the option of passing something by a pointer (e.g. a reference to a memory region). Java calls every function with a value (not a pointer), but the value of an Object is a reference to a memory region. See also the default toString() in your own classes.
I always find this a good example:
Dog foo = new Dog("Rocky");
modifyDog(foo);
System.out.println(foo.name); //Alice
public void modifyDog(Dog aDog)
{
aDog.name = "Alice"; //here you change the field 'name' of the object located in memory currently referenced by foo and aDog variables.
aDog = new Dog(); //since aDog is a copy of foo then this won't recreate foo object
}
While playing in Java. I saw different behaviour if an object is modified and given a value and different value if it is assigned a new object. Here is code that I made to show the result.
public class Test {
int i;
public Test(int j) {
this.i = j;
}
public static void main(String[] args) {
Test A = new Test(5);
Test N = new Test(5);
add(A);
makeNew(N);
System.out.println("Value of A.i= "+A.i);
System.out.println("Value of N.i= "+N.i);
}
private static void add(Test t) {
t.i+= 3;
System.out.println("Inside method add() t.i= "+t.i);
}
private static void makeNew(Test t) {
t = new Test(8);
System.out.println("Inside method makeNew() t.i= "+t.i);
}
}
Here is the output of the above code.
Inside method add() t.i= 8
Inside method makeNew() t.i= 8
Value of A.i= 8
Value of N.i= 5
In above example object A is modified to value 8. And object B is given a new object itself. But calling them back only object A shows new value. Object B shows the old value itself. Should not they be showing same value because both case are pass by refernce? I was expecting same value for A.i and N.i.
Here's what happens:
Test A = new Test(5);
Test N = new Test(5);
add(A); // method is add(Test t)
makeNew(N)// method is makeNew(Test t)
t = new Test(8);
System.out.println("Value of A.i= "+A.i);
System.out.println("Value of N.i= "+N.i);
Whenever you make a variable equal to an object and later use new on that object somewhere else like through another reference, your variable you set to the objects reference no longer points to whatever the new object is, but still holds onto the old. So if multiple variables at different scopes hold a reference, they all need a way to have them made equal to whatever the new object is or they no longer are in synch.
I think this will make you doubt clear:
You see N still point to the first object
In your makeNew, you're overwriting the reference to the existing object (that's passed in as the paramter) with your new test(8) object. However, that's local inside makeNew, so the original object sitting inside main(...) is not affected.
Java is pass-by-value. You pass the reference of an object as a value, and you can thus modify that object. However, you cannot modify the actual reference of an object and make it point to something else.
Your question has already been answered here: Is Java "pass-by-reference" or "pass-by-value"?
In Java you do not pass the actual object nor do you pass the reference to the object. You pass copy of the reference to that object. Now when you say
makeNew(N);
N which is the reference to new Test(5) is not passed but the copy of it's reference is passed. In the makeNew() function this copy points to some new object and print the value appropriately but the N will still point to the original object.
I have come across two scenarios.
One in which an array is passed as argument to a method and if it is updated in the called method, it is reflecting in the calling method as well.
But in the second scenario, a String Object is passed as argument. The object is updated in the called method, but it doesn't reflect in the calling method.
I want to understand what is the difference between two, even though in both cases, value (of reference) is passed as argument. Please see below snippets.
Scenario 1:
class Test {
public static void main(String[] args){
int a[] = {3,4,5};
changeValue(a);
System.out.println("Value at Index 1 is "+a[1]);
}
public static void changeValue(int b[]){
b[1] = 9;
}
}
Output:
Value at Index 1 is 9
Here, reference (Memory Address) related to array a is passed to changeValue. Hence, b is just pointing to same address as a does.
Hence, whether I say b[1] or a[1], it is referring to same memory address.
Scenario 2:
public class Test {
public static void main(String[] args){
String value = "abc";
changeValue(value);
System.out.println(value);
}
public static void changeValue(String a){
a = "xyz";
}
}
Output:
abc
If I apply the same logic here, String Object VALUE's reference (Memory Address) is being passed to changeValue, which is recieved by a.
Hence, now a should be referring to the same memory location as VALUE does. Therefore, when a="xyz" is executed, it should replace "abc" with "xyz".
Can someone please point out where my understanding goes wrong? Thanks in advance!!
Java passes all its arguments by value. This means that a copy of the pointer to the String is made, and then passed to the method. The method then makes the pointer point at another object, but the original pointer still points to the same String.
This is not the same thing:
in the first example, you pass an array reference as an argument, therefore you correctly expect it to be changed by manipulating the reference directly;
in the second example however, you pass an object reference, sure -- but you change the reference itself in the method. Changes to a are not reflected when the method returns.
Consider any object:
public void changeObj(Object o)
{
o = new Whatever();
}
a new object is created, but it won't change o in the caller. The same happens here.
You're doing different things; with the string you set the parameter value, with the array you set something belonging to the reference.
For an equivalent array example you'd need to try setting the array reference to a new array:
public static void changeValue(int[] b) {
b = new int[] { 42, 60 };
}
The original array won't be changed.
The difference here is simple, and it is not actually about immutability of strings, as some other answers (now edited or deleted) might have originally implied. In one version (with the string), you have reassigned the reference, and in other version (with the array), you haven't.
array[0] = foo; // sets an element, no reassignment to variable
array = new int[] { 1,2,3 }; // assigns new array
obj = "hey"; // assigns new value
When you reassign the variable, you are not going to observe that change outside of the method. When you change elements of an array without reassigning the array variable, you will observe those changes. When you call a setter on an object without reassigning the actual variable of the object, you will observe those changes. When you overwrite the variable (new array, assigning new value, creating new object, etc.) those changes will go unobserved.
Arguments are passed (or copied) by value. The variable inside the method has the same value as the variable on the outside at the beginning. The variables are not linked, and they are not aliases for one another. They just happen to contain the same value. Once you reassign the value to one of them, that is no longer true! The variable on the outside is not affected by the variable on the inside, or even another local variable. Consider
Foo foo = new Foo();
Foo other = foo;
foo.setBar(1);
int bar = other.getBar(); // gets 1
foo = new Foo();
foo.setBar(42);
int bar2 = other.getBar(); // still gets 1
foo and other only referenced the same object for a time. Once foo was assigned a new object, the variables no longer had anything in common. The same is true for your reassignments to the parameter variable inside your method.
Thank you all for answers and updates..
I understood the difference between scenario 1 and 2 as below..
In scenario 1, the array reference is passed. The called method just updates one of the elements pointed by the reference.
While in scenario 2, the reference is passed, but when the called method assigns "xyz" to the reference variable (pointer), it actually creates a new String Object and its reference is assgined to a local reference variable 'a' (Pointer now points a different objct).
The code in called method is as good as
a = new String("xyz");
Hence, the object in called method and calling method are absolutely different and indepenedent and have no relation with each other.
The same could have happened with scenario 1, if instead of doing
b[1] = 9;
I would have used
b = new int[] {8,9,10};
I understood, Mutability fundamentals would have come in action, if I might have done like below..
String a="abc";
a="xyz";
In this case, object "abc" was being pointed by 'a'. When 'a' is assigned the duty to point to a new object "xyz", a new object "xyz" is created, which is not replacing the existing object "abc". i.e. "abc" is still existing but has no reference variable to keep itself accessible anymore. This non-replacement property is because of Immutability of String.
I read many articles and all says Java is pass by value. But i still don't construe the difference between pass by value and reference. I wrote a sample program and it executes like this..
public class PassByValue {
private int a;
private int b;
public PassByValue(int a, int b) {
this.a = a;
this.b = b;
}
public static int mul(int a, int b) {
int z = a * b;
System.out.println("The Value of Z inside mul: " + z);
return z;
}
public static void main(String args[]) {
int z = 100;
int x = 40;
int y = 20;
mul(x,y);
PassByValue pass = new PassByValue(x,y);
mul(pass.a,pass.b);
System.out.println("The Value of Z" + z);
}
}
Execution
800
800 and
100
Can anyone explain me these questions...
What is Pass By Value means...
Answer: Its just passing the numbers or value stored in the variable to a function. Am i right or wrong.
How do you say Java is Pass By Value?
Why is Java is Pass By Value and not by reference?
Does the above program Tries shows an example of Pass by value and Reference... but still does things via Pass by Value only... I wrote that program.
The confusion is probably due to the fact that a variable can't contain an object in the first place. A variable can only contain a reference to an object. (In other words, objects aren't passed at all, not by reference, not by value.)
Once you realize this, it is quite clear that nothing is pass-by-reference in Java. A variable refering to an object stores a reference, and this reference is passed by value.
1. What is Pass By Value means...
Answer: Its just passing the numbers or value stored in the variable to a function. Am i right or wrong.
That's right. The value contained in the variable is passed, and not the variable itself.
1. How do you say Java is Pass By Value?
Java is pass by value because primitives are passed by value, and references are passed by value. (Objects are never passed.)
You can't implement a swap method in Java for instance. I.e., you can't do
String str1 = "hello";
String str2 = "world";
swap(str1, str2);
// str1 can't refer to anything but "hello"
// str2 can't refer to anything but "world"
2. Why is Java is Pass By Value and not by reference?
As explained above, even references are passed by value.
You are right in your answer, but you are lacking detail. If you do
Dog d = new Dog()
d is a reference to an instance of Dog, i.e. What pass by value means is that you when pass d into a method
walkDog(d);
the a copy of the reference (i.e. the value of the reference, not the reference itself) to the Dog is passed into the method. So you have 2 references to the one instance of the Dog, the one in the calling scope, and the one in the called scope. Lets say in the walkDog method there is a line
d = new Dog();
the d reference in the method only points to the new Dog. The original reference where the method was first called still points to the original Dog. If Java had pass by reference, the same reference, not a copy of the reference would be used in the method, and so changing the value of the reference would affect the reference in both the calling and the called scope.
EDIT -- based on your comment, I want to make on thing clear. Since the reference in the original scope and the method scope both point to the same object, you can still change things on that object in both scopes. So if you do
d.drinkWater();
in the walkDog method, and drinkWater changes some variable on the dog object, then since both references point to the same object, which was changed.
It's only a distinction between what the references actually are in each scope. But it does come up a lot.
You can think of pass-by-value as passing only the value contained in the variable and not the variable itself. So then the value is copied into another temporary variable. In contrast, you can think of pass-by-reference as passing the actual variable and no temporary copies are made, so that any changes in the variable is 'saved'. Although there is more to it, it might be easier way to thinking about it
I think instead creeping around if Java supports pass by reference or values, one should be clear about the way of using the instances of the classes in Java in his implementation. It all happens to be the type of instances - mutable/immutable which is gonna decide the way we pass things to the functions! That's up to you to explore this difference!
Let me clarify my argument of why there is no need of chasing back at passing what?! Consider this...
First Code:
void foobar(int *a){
printf("%d", *a);
}
int main(){
int a = 5;
foobar(&a);
return 0;
}
Here in this C code, what are you passing... the address of the variable 'a'. This happens to be the pass by reference! :)
Let us consider another one...
Second Code:
void foobar(int* a){
printf("%d", *a);
}
int main(){
int a = 5;
int *p = &a;
foobar(p);
return 0;
}
Here in this C code, what am I passing....? The value of the variable 'p', doesn't matter whether it is pointer or something :P
So what do you call this as pass by value/pass by reference? I leave this to you! But all we need to look at is how we gonna implement... :)
So in Java... with what we pass we can say - It supports "Pass by value" or "Pass by reference of some instance" and not "Pass by reference"
***Only thing which I can clearly conclude is with the primitive data types in Java. Since there is no pointers with which one can edit the content of a byte without the actual variable, we can't have pass by reference for them(I mean the primitive data types) in Java.
If I have a member variable such as this (declared in the body of a class)
private Dot[] dots=new Dot[numDots];
I loop through all members of this array, and:
1) Pass every Dot object to a function of another class, which:
2) Passes it to yet another function of a 3rd class, if some conditions are met
3) And the 3rd class changes some properties of the Dot object
then when this object is returned to the original/parent class, would those changes to its properties have retained? Or would it be treated like a local variable by the 2nd/3rd functions?
Yes, the changes to the properties are retained. Java is 100% pass-by-value, however, when you pass an object, the "value" passed is truly a pointer to the object. Thus, when you change an object in a method, you're changing the actual object passed in.
That is, if you have the following method, then the calling method will see the changes:
private void updateMyDot(final Dot aDot) {
aDot.dotColor = new Color(255,255,255);
}
but if you do the following, then the calling method will not see the changes.
private void updateMyDot(/* not final */ Dot aDot) {
aDot = new Dot();
aDot.dotColor = new Color(255,255,255);
}
In the second example, the caller will not see any changes and will not see the newly created Dot object.
Objects are passed by [reference value where the value is the reference] (things that inherit from Object), primitive values (int, long, double, etc.) are passed by value.
This means that when a primitive is passed from a caller to method it is copied, whereas with an object a [value of the] reference is passed.
Which in turn means that when an object is mutated by a method the caller sees those changes because it has a reference to the same object.
Conversely when a method mutates a primitive the caller does not see the changes as the method is working on a copy.
[reason for the edits]
If Java had pass by reference then you could do this:
Object x;
x = new Integer(42);
foo(x);
System.out.println(x.getClass()); // pass by reference would have it print out java.lang.Float
where foo is defined as:
void foo(Object o)
{
o = new Float(43);
}
Since Java passes the reference by value o = new Float(43); is allowed - but the value in the caller will remain as the new Integer(42);