My teacher asked me to answer a series of questions. And two of them confuse me greatly.

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

I can not understand the meaning of the question (((

  1. How are parameters passed to methods in Java?

I googled this question and understood that by always by value, but what exactly it means is not understood.

Could you help me understand this situation?

  • 3
    Change the teacher! Say that you have to ask him questions, not him to you. :) - Vlad from Moscow
  • No, this is something like an oral test. I had to figure it out. I have a good teacher, please do not offend him. )))) - Pavel

3 answers 3

Why can't I change an object reference in a method?

Because the method is passed not a link , but an object that contains a copy of the link .

How are parameters passed to methods in Java?

All arguments (both primitive types and objects) in Java are passed by call by value . Here you should immediately make a reservation that the object essentially represents the link, therefore, when the object changes in the method, the original object will also change.


You can read more in the “Detailed Consideration of the Arguments for Passing Arguments” in the complete Java manual by Herbert Schild.

  • >>> Why can't I change an object reference in a method? Because a copy of the object is passed to the method (which refers to the same place where the original object was referenced). <<< - Pavel
  • here thanks it helped! - Pavel
  • Why then the original, only memory to overload? Sorry if I ask stupidity. - Pavel
  • @Paul, This is rather a question for the language developers :) And besides, both objects will refer to the same memory area. - post_zeew
  • four
    "a copy of the object is passed to the method" - Strange statement. A copy of the object (with reservations) is actually created by the clone () method, and a copy of the object reference is passed to the method. - m. vokhm

As Vlad from Moscow hinted at in the commentary on the question, the question is rather 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 in the method you can change the link in general. Strictly speaking, in Jave they usually speak not about references to an object, but about variables (fields, arguments) of an object type. But in fact, the value of such variables are references to objects. Methods as their arguments receive copies of these links and can do whatever they want with them (i.e. assign them values ​​of references to other objects or null - "empty reference"), which does not affect the values ​​of variables that were passed to the method calling him So here's 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 class String with the value "Cannot change links?";
  2. Assigns a reference to it to the variable string;
  3. Calls the qq () method and passes it a copy of the string variable (i.e., creates a second reference to the same string "Cannot change references?")
  4. The qq () method outputs to the console the contents of that object, the link to which is contained in its parameter — that is, the same “cannot?”;
  5. The qq () method assigns a new value to its parameter s - the link to the new line “Something New ...” - the second link to “no” disappears, but the initial variable string in the main program does not change at all and still contains a link to the same original "no?";
  6. The qq () method prints a new line ("Something New ...") and returns control to the main program (main method);
  7. The main () method prints the contents of the object that is contained (that is, the link to which is contained) in the string variable — this is still the original string "Can't change links?"

The output will be:

 Нельзя менять ссылки? Что-то новое Нельзя менять ссылки? 

But it must be clearly understood that although the method cannot change the value of an object variable passed to it as a parameter (that is, a reference to an object), it can change the object itself for a sweet soul! For example, in such a program

 import java.util.ArrayList; 
public class TestQQQ { static void qqq(ArrayList list) { list.add("можно."); }
public static void main(String[] args) { ArrayList strings = new ArrayList(); strings.add("А объекты менять...?"); qqq(strings); System.out.println(strings); } }
the qqq () method adds to the list, the link to which it received, a new line "can be.", and as a result we get the following output:
[А объекты менять...?, можно.]

  • You have explained very extensively, thank you very much there is something to think about, and if I understood everything correctly, then you don’t contradict the post_zeew answer that a copy of the link is passed to the method. Of course, the objects themselves can be changed. Otherwise, the meaning of creating the method itself would be lost because the method is often created for this. Or is there still a contradiction? Now I will think a copy of the link is still passed to the method or the original? What do you think? - Pavel
  • one
    A copy of the link is passed to the method. Contradiction, apparently, no; just in the first answer he did not quite accurately put it. Then he corrected and it became better, but now, I look, he corrected again, and again it is difficult to understand what he means. To remove all doubts, copy my code and play with it - you will understand everything yourself. - m. vokhm
  • Yes, everything is clear. - Pavel

Why can't I change an object reference in a method?

When an object is transferred to a method, it simply copies the link to it (No copies of the object are created during the transfer!). And by using it you communicate with the original object. From here it should be clear why when overwriting a new object in this link, the old one does not change. A simple example for clarification:

 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?

Primitives by value, objects - as I described above (I do not know how correctly this method is called).

Update: thanks @Roman , the correct name for the method of transferring objects to the method is call by sharing

  • As far as I remember, this is formally called still passing by value, but it stipulates that the value of an object variable is a reference to an object, so that when the method is called, a second reference occurs. This is important to understand when it comes to garbage collection and similar things. - m. vokhm
  • Thanks it seems now I finally understood everything! - Pavel
  • 2
    Wikipedia says that this method is called “ call to use ” (it sounds like something not really, yes). - Roman
  • @Roman, thanks for the link! It is useful - for beginners to show :) - m. vokhm