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); } }
- Creates a new object of class String with the value "Cannot change links?";
- Assigns a reference to it to the variable string;
- 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?")
- 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?”;
- 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?";
- The qq () method prints a new line ("Something New ...") and returns control to the main program (main method);
- 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:
[А объекты менять...?, можно.]