Another interview question to test your Java Foundation is solid.
Title: What is the result of the following code?
public class TestValue {public static void Test (String str) {str= ' world ';//code 3}public static void Main (string[] args) {St Ring string = "Hello"; Code 1test (string); Code 2system.out.println (string); Code 4}}
The result of the operation is: Hello
Parse: When run arrives at Code 1 o'clock, the system creates a memory space in the heap memory to generate a String object and sets the value of the object to "Hello". The object is then assigned to a string variable in the stack memory to refer to. The variable string is a reference object that is actually assigned, and this reference holds the address value of "Hello" in the heap memory.
Run the arrival Code 2, enter the test (string str) method, and a copy of the variable string (reference) value is passed to the test method. Assigns a copy of the string variable to the parameter str of the test method. the variable str in the variable string and the test () method is a string object that references the "Hello" value in memory.
run reaches Code 3 o'clock, the system is in heap memory opens up a memory space to test () The variable in the method str is
Run at the end of Code 4 o'clock, thetest (String str) method ends, the variable str function in the method disappears, the variable str is not in the stack memory, and the variable string. A string object with a value of "Hello" in heap memory is still referenced by a variable string, and a string object with the value "world" is not referenced. so the print result is: Hello
Below is the memory.
Of course if we really need to change the value of the object, we can try to use the StringBuffer object to handle it. The code is as follows
public class TestValue {public static void main (string[] args) { StringBuilder String = new StringBuilder ("Hello");
change (string); System.out.println (string); } public static void Change (StringBuilder str) { str.delete (0, 5). Append ("World"); } }
The print result is: world
Readers can also refer to the following links:
http://www.programcreek.com/2013/09/string-is-passed-by-reference-in-java/
==================================================================================================
Ouyangpeng welcome reprint, sharing with people is the source of progress!
Reprint please keep the original address : Http://blog.csdn.net/ouyang_peng
==================================================================================================
My Java Development Learning journey------>java string objects as arguments