The value of a pass or a reference is a fundamental problem in Java, and it is a question that is often examined during the written examination.
Topic 1: Write out the output of the following program.
Public class Test {publicstaticvoid changevalue (int= 0;} Public Static void Main (string[] args) {int value =; ChangeValue (value); System.out.println (value);}}
The output results are obtained.
Answer:
2010
This topic examines the problem of parameter passing in Java methods. The parameters of a method in Java are passed as a value pass, regardless of whether the argument is a base type or a reference type, we pass in the past a copy of the value, which is stored as a local variable of the method in the stack (stack).
For the above ChangeValue () method, passed in is a copy of the variable value, modified in the ChangeValue () method is only a local variable of the method, does not affect the variable passed in as a parameter, both squarely.
Topic 2: Write out the output of the following program.
Public class Test {publicstaticvoid changlist (List list) {List.add ("BBB");} Public Static void New ArrayList (); List.add ("AAA"); changlist (list); System.out.println (List.size ());}}
Answer:
2
Description
When the main () method calls the Changelist () method, the list variable in the Changlist () method is a copy of the list variable of the main () method, which points to the same ArrayList object in the heap. Therefore the same object is also manipulated.
Topic 3: Write out the output of the following program.
Public class Test {publicstaticvoid= str + "BBB";} Public Static void = "AAA"; changestring (str); System.out.println (str);}}
Answer:
Aaa
Description
The Changstring () method only causes the local variable STR to point to a completely new string object "AAABBB", which has no effect on the STR variable in the main () method.
Summary of the Java method parameter passing:
The underlying data type (Int,char, ... ) Values, object types (objects, arrays, containers ...) ) to pass the reference.
It is said that the Java method parameters are transmitted values, the understanding of different ways. The reference itself is also a value (object address).
The value is passed as a copy of the value. The modification of the copy in the method does not affect the caller.
The reference is passed as a copy of the reference. At this point, the formal parameters and arguments point to the same memory address. Modifications to the object that the reference replica points to, such as modifying object properties, container contents, and so on, can affect the caller. Modifications to the reference replica itself (object address), such as NULL, are re-directed to other objects without affecting the caller.
As long as you know the reference, it is also a copy of the passed reference, it is relatively easy to understand.
Java method parameter passing question