-1

I know there have been several posts explaining argument passing in Java. I also know that the arguments are passed by value but the value is the reference to the object. Say I have the following 2 mthods.

public void append(List<String> list){
    list.add("some string");
}

public void incr(int count){
    count++;
}

If I call the first method, the object list gets modified and the modified value exists after the method call too. But when I call incr(count), the modified value of count is lost once the method call returns.

Why is it that in some cases, the value gets modified but in the other it does not?

Nik
  • 5,515
  • 14
  • 49
  • 75
  • `list` is a reference, referring to a List object that exists outside of the parameter list. `count` is a value, not a reference, and its value only exists in the parameter list. – Hot Licks Sep 15 '14 at 21:49
  • count++ is equivalent to count = count + 1. It **assigns** a new value the the `count` variable. The first snippet doesn't assign a new list to the `list` variable. It only modifies the content of the list object. – JB Nizet Sep 15 '14 at 21:49
  • Eg, you cannot do `list = someOtherList;` and change which List object the caller refers to. – Hot Licks Sep 15 '14 at 21:51
  • Nik: You are doing two different things. `count++` means `count = count + 1`. You are _reassigning_ `count`. Try doing the same in the other method: `list = new ArrayList()`. That new list will only exist in that method, the original list won't get modified. – BackSlash Sep 15 '14 at 21:52
  • "but the value is the reference to the object *if the parameter is a reference type (ie, it refers to an object)*" – Hot Licks Sep 15 '14 at 21:52
  • `Why is it that in some cases, the value gets modified but in the other it does not?Why is it that in some cases, the value gets modified but in the other it does not?` - The value gets modified in both cases. The difference is that in one case you've modified an object you have a reference to in the calling code, so you can see that change. – azurefrog Sep 15 '14 at 21:53
  • In none of the cases the value passed to the function gets modified (only the local copies of them). However the *state of the object* (i.e. it's fields) passed to `append` is changed. But since you use a primitive type as parameter of `incr`, there is no state. You won't see a effect either, if you try to assign a new value to `list` in `append` (e.g. `list = null;`); the changes wouldn't be visible outside of the method. – fabian Sep 15 '14 at 22:15

1 Answers1

-1

I also know that the arguments are passed by value but the value is the reference to the object.

That is not what java does. Java is pass by value. If something is a reference type, then that reference is passed by value. But that is not the same as being pass by REFERENCE. So, in your second example, the count variable is passed by value, so your changes are lost.