Java. Why can't I change the object reference in the method?

My teacher asked me to answer a number of questions. And two of them are very confusing to me.

  1. Why can't I change the object reference in the method?

I can't understand the meaning of the question(((

  1. How are parameters passed to methods in Java?

I Googled this question and realized that by is always by value but I didn't understand exactly what it means.

Could you help me figure this out? situations.

Author: Kromster, 2016-10-23

3 answers

Why can't I change the object reference in the method?

Because the method is passed not a reference, and the object, which contains a copy of the reference.

How are parameters passed to methods in Java?

All arguments (both primitive types and objects) in Java are passed when calling by the value. Here you should immediately make a reservation that the object is essentially a reference, therefore, when changing the object in the method, the source object will also change.


For more information, see "A detailed discussion of the features of argument passing" in the complete guide to Java by Herbert Schildt.

 4
Author: post_zeew, 2016-10-24 11:51:13

As Vlad from Moscow hinted in the comment to the question, the question is quite strange, and in my opinion it is not quite correct - either your teacher is not very good at expressing his thoughts, or you somehow slightly distorted his question.

The fact is that you can actually change the link in the method. Strictly speaking, Jave usually does not talk about references to an object, but about variables (fields, arguments) of the object type. But in fact, the value of such variables are references to objects. Methods in they get copies of these references as their arguments and can do whatever they want with them (i.e. assign them the values of references to other objects or null - an "empty reference"), which does not affect the values of variables that were passed to the method when it was called. So here is the code


public class TestQQ {
static void qq(String s) { System.out.println(s); s = "Что-то новое..."; // Это ссылка или не ссылка меняется ? System.out.println(s); }
public static void main(String[] args) { String string = "Нельзя менять ссылки?"; qq(string); System.out.println(string); } }
  1. Creates a new object of the String class with the value " Can't change references?";
  2. Assigns a reference to it to the string variable;
  3. Calls the qq() method and passes it a copy variable string (i.e. creates a second reference to the same string "Can't change references?")
  4. The qq() method outputs to the console the contents of the object referenced in its parameter - i.e. the same "can't?";
  5. The qq() method assigns a new value to its parameter s-a reference to the new string "Something new...", -- the second reference to" can't " disappears, but the original string variable in the main program does not change in any way and still contains a reference to that the same original "can't?";
  6. The qq() method prints a new line ("Something new...") and returns control to the main program (the main method);
  7. The main() method prints the contents of the object that is contained (i.e. the reference to which is contained) in the string variable - this is still the original string "Can't change references?"

The output will be as follows:{[1]}

But at the same time, it must be clearly understood that although the method can not change the value of the object the variable passed to it as a parameter (i.e., a reference to the object), it can change the object itself for a sweet soul! For example, in such a program {[2]} the qqq() method adds a new string "possible." to the list that it received a reference to, and as a result, we get this output:
[А объекты менять...?, можно.]

 7
Author: m. vokhm, 2016-10-24 11:24:46

Why can't I change the object reference in the method?

When passing an object to a method, it simply copies the reference to it (No copies of the object are created during the transfer!). And you are already using it to communicate with the source object. From here, it should be clear why when a new object is overwritten in this reference, the old one does not change. A simple example to clarify:

List<Object> list1 = new ArrayList<>(); //Создаём объект и кладём в ссылку
List<Object> list2 = list1; //Просто копируем ссылку
list2.add(new Object); //Через копию ссылки мы меняем исходный объект в list1
list2 = new ArrayList<>(); //Хоть мы и переписали в ссылку новый объект, 
//исходный никуда не делся, он всё также лежит в list1.

How are parameters passed to methods in Java?

Software primitives by value, objects - as I described above (I don't know what this method is called correctly).

Update: thank you @Roman, the correct name of the method for passing objects to the method is call by sharing

 4
Author: Roxio0, 2017-04-13 12:53:25