Java is a pass value or a pass reference

xiaoxiao2021-03-06  87

All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references. (Excerpt from http://www.javagalaxy.com:8080/Interview/index.jsp?Intv=18) Parameters of all methods in Java are transmitted. However, Java is indeed by reference to operating objects, and all object variables themselves are referenced.

It turns out that all methods are passing values, and there is no passage: to take a few examples to see:

Examples 1: public class TestRef1 {public static void test (StringBuffer str) {str = new StringBuffer ( ", World!");} Public static void main (String [] args) {StringBuffer string = new StringBuffer ( "Hello") TEST (STRING); system.out.println (string);}} Run: Hello

Example 2: Public Class TestRef2 {public static void test (string str) {str = ", world!";} Public static void main (string "args) {string string = new string (" hello "); test (String ); System.out.println (string);}} Run results: Hello

Example 3: Public Class TestRef3 {Public Static Void Test (StringBuffer Str) {Str.Append (", World!");} Public static void main (string [] args) {stringbuffer string = new stringbuffer; "Hello"); Test (string); system.out.println (string);} Run results: Hello, World!

First of all, I think: The above three examples are all transmitted, and there is no passage.

Second, we believe that: 1. Different references can point to the same object; 2, the value of the String object is not changeable (like b = "world"; b = a; this situation is not changed "world" The value of the object, but changed its reference B to another String object a); 3, "=" is an assignment operator. The assignment is modified is an object reference, not the object itself.

According to the above mentioned above, Str = ", World!"; And Str = New StringBuffer ("World!"); All assignment operations, modified the reference to the object STR, make it point to a new object, and There is no change to the object itself (here, ", World!" And New StringBuffer (", World!")). So String is not affected. 2, str.append (", world!"); This change is the object itself, not an object reference. The above is a personal point of view, welcome to correct!

转载请注明原文地址:https://www.9cbs.com/read-107822.html

New Post(0)