Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Pass by value problem?

Tags:

java

We know Java supports only "pass by value" .If I pass a collection for eg., a hash table to a function then the modifications to this collection inside the function should not be updated outside this function.But this is not the case in Java?.How do we conclude this?

Please anyone conclude this discussion with a proof...

like image 928
Sidharth Avatar asked Dec 03 '22 13:12

Sidharth


2 Answers

Passing an object by value to a method means that the method is given a copy of the reference to the object, but it is still possible to access the object members from within the passed reference copy. In the case of collections, this includes invoking the methods to add and remove objects, and of course to modify the contained objects themselves.

like image 162
Konamiman Avatar answered Dec 24 '22 09:12

Konamiman


You are confusing what "value" means. If you are dealing with objects, this means that any changes of the value of the reference are not reflected to the outside. A straightforward example that shows this behavior is be something like this:

public void foo() {
  String s = "example";
  String param = s;
  bar(param);
  assert s == param : "The value of parameter reference was not modified";
  assert param.equals("example");
}

public void bar(String param) {
  param = "something different";
}

Passing by value does, however, not mean that you cannot change the internal state of the object. This is perfectly possible and has consequences to the outside:

public void foo() {
  List<String> l = Arrays.asList("example");
  List<String> param = l;
  bar(param);
  assert s == param : "The value of parameter reference was not modified";
  assert !param.get(0).equals("example") : "bar changed the internal state of the parameter";
  assert !l.get(0).equals("example") : "bar changed the internal state of the list that is reference equal to the parameter";
}

public void bar(List<String> param) {
  param.set(0, "something different");
}

Of course, such changes of the internal state of an object are reflected up all the way in the caller stack, which might lead to unforeseen side effects. This is the reason why the immutable object pattern was introduced. In the Java standard library, java.lang.Object and java.lang.String are examples for classes that implement this pattern. However, Java does not provide a language feature where where you can state that a class implements this pattern, so you must rely on JavaDoc and/or source code of the class to be sure an object is immutable.

like image 26
nd. Avatar answered Dec 24 '22 10:12

nd.