Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer with java and string variable [duplicate]

Tags:

java

string

I gave a value (as variable) to a String variable.

The problem is that when I change this value, it doesn't change the other variable :

Code :

 String test = "hello";
 String myname = test;
 test = "how are you ?";

The output of myname is "hello"

I want that the output be "how are you?" the new value of test; how to do it without give the value again like :

myname = test;

I don't want to give the value again because I my code I got a lots of variables that got the test variable as value, I want to do the shortest way.

like image 316
LeSam Avatar asked Feb 07 '26 03:02

LeSam


1 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?

like image 52
MattSenter Avatar answered Feb 12 '26 14:02

MattSenter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!