Parsing of string-type parameter passing problems in Java

Source: Internet
Author: User

I. Introduction of examples

public class Stringasparamofmethoddemo {public static void main (string[] args) {Stringasparamofmethoddemo sapm = new Strin Gasparamofmethoddemo (); Sapm.testa ();} private void TestA () {String originalstr = "original"; System.out.println ("=======test A begin:======="); SYSTEM.OUT.PRINTLN ("1.The outer string:\n" + originalstr); simplechangestring (ORIGINALSTR);    SYSTEM.OUT.PRINTLN ("3.The outer String after inner change:\n" + originalstr);    System.out.println ("=======test A end.=======");    System.out.println ();    } public void Simplechangestring (String original) {original = original + ' is changed! "; System.out.println ("2.The changed inner string:\n" + original);}




The logic of this code is this: first assign a string type of local variable, and then put the variable as a parameter into a method, in this method to change the value of the variable.

after compiling the run, we find that the output is this:

=======test A begin:=======

1.The outer String:

Original

2.The changed inner String:

Original is changed!

3.The outer String after inner change:

Original

=======test A end.=======


The result shows that the re-assignment of a variable of type string within the method does not have any effect on the prototype of the variable.

Well, the logic and running results of this example are all clear, so let's analyze this little program. Before we do this, we'll look at the so-called "pass-through" and "pass-through" problems in Java.


Ii. "pass-through" and "pass-through" issues in Java

The conclusion is:

in Java, when a primitive type is passed into a method as a parameter, no matter how the parameter is changed within the method, the external variable prototype is always the same, and the code resembles the example above:

int number = 0;

ChangeNumber (number) {number++};//change the input int variable

System.out.println (number);//When number is still 0

This is called "value passing", where a method operates on a parameter variable (that is, a copy of a value of a prototype variable) that changes only one copy of the prototype variable, not the variable itself. So the variant prototype doesn't change with it.

but when a method passes in a non-primitive type (that is, a variable of an object type), the method changes the parameter variable and the variant prototype changes as well, and the code is similar to the example above:

StringBuffer strbuf = new StringBuffer ("original");

Changestringbuffer (strbuf) {strbuf.apend ("is changed! ")}//Change the StringBuffer variable sent in

System.out.println (STRBUF);///At this point the value of Strbuf becomes original is changed!

This attribute is called "reference Pass", also called the address, that is, the method operation parameter variable is a reference to copy the variable, and then by reference to find the variable (here is the object) the real address and manipulate it. When the method ends, the parameter variable inside the method disappears. But to know that this variable is only a reference to the object, it only points to the real address of the object, not the object itself, so it does not have any negative impact. Looking back at the prototype variable, the prototype variable is essentially a reference to that object (the same as the parameter variable), and the change to the object referred to in the parameter variable is simply a change to the object that the prototype variable refers to. So the object represented by the prototype variable is changed, and the change is preserved.

but the string type is non-basic in the Java language! Why hasn't the change in the method been preserved?

Third, about the string parameter transfer problem of one of the distortions?? Assigning values directly to Objects

There are two common explanations for how a variable of type string is passed as a parameter in the same way as a primitive type variable.

One explanation is that assigning a value to a variable of type string does not create a new object, but instead directly assigns a value to the string, so Java Consider this variable of type string as a basic type. That is, it should be string str = new String ("original"), instead of string str = "original";. Is that the problem? Let's take a little makeover of the previous example and see what happens after the run. The code after the transformation is as follows

private void Testb () {    String originalstr = new String ("original");    System.out.println ("======= Test B Begin =======");    SYSTEM.OUT.PRINTLN ("1.The outer String:" + originalstr);    Changenewstring (ORIGINALSTR);    SYSTEM.OUT.PRINTLN ("3.The outer String after inner change:" + originalstr);    System.out.println ("======= Test B End =======");    System.out.println ();    }    public void Changenewstring (String original) {    original = new String (original + "is changed! ");    System.out.println ("2.The changed inner String:" + original);    }




The operating result is:

======= Test B Begin =======

1.The outer string:original

2.The changed inner string:original is changed!

3.The outer String after inner change:original

======= Test B End =======

practice has proved that this statement is wrong.

in fact, the difference between the direct assignment of a string and the assignment of an object with new is only different in the way it is stored.

when a string is directly assigned a value, the value referenced by a variable of type string is stored in the constant pool of the class. Because "original" itself is a string constant, and the string is an immutable type, the variable of type string is equivalent to a drop reference to a constant. In this case, the size of the variable's memory space is determined at compile time.

The new object is stored in the memory space of the string object by storing "original", which is performed at run time. In this case, Java does not treat the string "original" as a constant, because it appears as a parameter to create a string object.

Therefore, there is no direct connection between the assignment method of string and its parameter-value problem. In short, this explanation is not a positive solution.

four, on the string parameter transfer problem of the two distorted?? "=" Variable value and method variable value

This argument says: "In Java, change the value of the parameter in two cases, the first, using the assignment number" = "directly assigned to change it, and the second, for some object reference, through a certain way to change its member data, such as through the object itself method. In the first case, the change does not affect data other than the method passed into the parameter variable, or directly to the source data. The second method, in contrast, affects the source data?? Because the object that the reference indicates does not change, changing its member data is essentially a change to that object. ”

Or the old way, write the demo, do a little experiment, the code is as follows:

private void Testb () {    String originalstr = new String ("original");    System.out.println ("======= Test B Begin =======");    SYSTEM.OUT.PRINTLN ("1.The outer String:" + originalstr);    Changenewstring (ORIGINALSTR);    SYSTEM.OUT.PRINTLN ("3.The outer String after inner change:" + originalstr);    System.out.println ("======= Test B End =======");    System.out.println ();    }    public void Changenewstring (String original) {    original = new String (original + "is changed! ");    System.out.println ("2.The changed inner String:" + original);    }



 

The results are as follows:

=========test C begin=========

1.The outer string:original

2.The changed inner string:original is changed!

3.The outer String after inner change:original

=========test C end=========

This proves that the problem is not here, yet another explanation has died out under the practical argument.

What is the reason for this situation?

Five, the crux of the string parameter transfer problem

public string (string original) {int size = original.count;char[] OriginalValue = original.value;char[] V;  if (originalvalue.length > Size) {     //the array representing the string is bigger than the new     //string itself .  Perhaps this constructor was being called     //in order to trim the baggage, so make a copy of the array.            int off = Original.offset;            v = arrays.copyofrange (OriginalValue, off, off+size); } else {     //the array representing     the string is the same//size as the string, so no point in making a copy.
   
    v = OriginalValue; }this.offset = 0;this.count = Size;this.value = v;    }
   



Perhaps you notice the char[inside], which means that the storage of the string is actually implemented by char[]. What do you think? is actually a layer of window paper. I don't know if you remember those basic types of wrapper classes defined in the Java API. For example, Integer is the int wrapper class, float is the packing class of float and so on. The value operations on these wrapper classes are actually implemented by their corresponding basic type operations. Are you feeling something? Yes, string is equivalent to the wrapper class of char[]. One of the characteristics of a wrapper class is that it reflects the nature of its underlying type when it operates on its value. In the case of parameter passing, the wrapper class is the embodiment. Therefore, the interpretation of the results of the presentation of string in this case is naturally derived. Similarly, the wrapper classes such as Integer, float, and string behave the same in this case.

The integer example is as follows:

private void TestD () {        Integer originalint = new Integer (123);        System.out.println ("=========test D begin=========");        SYSTEM.OUT.PRINTLN ("1.The outer Integer:" + originalint);        Changeintwithmethod (originalint);        SYSTEM.OUT.PRINTLN ("3.The outer Integer after inner change:" + originalint);        System.out.println ("=========test D end=========");        System.out.println ();      }        private static void Changeintwithmethod (Integer original) {    original + = 456;    System.out.println ("2.The changed inner Integer:" + original);    }




The result is:

=========test D begin=========

1.The outer integer:123

2.The changed inner integer:579

3.The outer Integer after inner change:123

=========test D end=========

Parsing of string-type parameter passing problems in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.