Is this a question that is often asked during an interview? In the process of doing the project, one of the students because of useless, resulting in a bug, but before the test! Originally I would like to take this opportunity to share the Java method of the mechanism, but after a few days of study, understand, found on-line blog basically no one can see clearly after the clear, speak is very swallowed. Think it's really not easy to really explain the problem to white? To understand the stack and heap of the JVM, and the meaning of references and assignments in Java. I can not clearly understand now, but should not be misused now, is the method call, know how to do can change the value of the passed parameter, how to do is not change the value of the passed parameter. Here's a little test program, do you know what this program will promise?
Public classTest { Public Static voidMain (string[] args) {StringBuffer a=NewStringBuffer ("A"); StringBuffer b=NewStringBuffer ("B"); inti = 5; Operate (A, B, i); System.out.println (A+ "," + B + "," +i); } Public Static voidOperate (StringBuffer x, StringBuffer y,intj) {x.append (y); Y=x; Y.append (C); J= 1; }}
Rule summary: Java parameters, whether primitive or reference type, pass a copy if the parameter type is the original type, then a copy of the parameter is passed in, that is, the value of the original parameter, which is the same as the value of the previous argument. If you change the value of a copy in a function, the original value is not changed. If the parameter type is a reference type, then a copy of the reference parameter is passed in, and the copy holds the address of the parameter. If you do not change the address of the copy in the function, but change the value of the address by changing the address, then the change within the function will affect the parameters passed in. If you change the address of a copy in a function, such as when you perform an assignment such as a= other objects, a=new, and so on, you actually point A to the new position, the original value outside the function does not change.
How Java methods are passed by value