Pointer with java and string variable

This question already has an answer here:

  • Passing a String by Reference in Java? 13 answers

  • First you are assigning the value "hello" (at some place in memory) to test :

    test --------------> "hello"
    

    Then, you are setting myname to the same location in memory.

    test --------------> "hello"
                      /
    myname ----------/
    

    Then, you are assigning the value "how are you?" at a new location in memory to test :

                       -> "hello"
                      /
    myname ----------/
    
    test --------------> "how are you?"
    

    It's all about the pointers.

    EDIT AFTER COMMENT

    I have no idea what the rest of your code looks like, but if you want to be able to update a single String and have the rest of the references to that String update at the same time, then you need to use a StringBuilder (or StringBuffer if you need synchronization) instead:

        StringBuilder test = new StringBuilder("hello");
        StringBuilder myname = test;
        StringBuilder foo = test;
        StringBuilder bar = test;
        test.replace(0, test.length(), "how are you?");
        Assert.assertEquals("how are you?", test.toString());
        Assert.assertEquals("how are you?", myname.toString());
        Assert.assertEquals("how are you?", foo.toString());
        Assert.assertEquals("how are you?", bar.toString());
    

    Got it from there?


    It sounds like you need to learn about the difference between a reference variable and the object that a variable refers to. Let's look at what your code does:

    String test = "hello";
    

    This assigns the reference variable test to refer to a constant String object with the value "hello" .

     String myname = test;
    

    Now the reference myname refers to the same String object as test does.

    test = "how are you ?";
    

    Now test refers to a new String object with the value of "how are you ?" . Note that this does not change myname , as you have seen.


    The problem is that String is immutable so "how are you ?" is a new object. Thus myname still refers to the old object "hello" .

    Solution 1: Don't use two references. Why not just use test throughout your code if there's only one object?

    Solution 2: Have the two references point to the same object, but use a mutable object. eg use StringBuilder or StringBuffer instead of String .

    链接地址: http://www.djcxy.com/p/20880.html

    上一篇: 如何使字符串添加到字符串功能?

    下一篇: 指针与Java和字符串变量