Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this variable get changed?

The following code produces this output:

aaab -> aabb -> abbb -> bbbb

My goal is to get it to look like this:

aaab -> aaba -> abaa -> baaa

But I am having a hard time figuring out why I am getting this result.

    String abcd = 'abcd';
    int l=3;
    byte[] word=new byte[]{abcd[0],abcd[0],abcd[0],abcd[0]};
    System.out.println(new String(word)); // print: aaaa
    while (l >= 0) {
        byte[] present=word; // !!!
        present[l + 1 - (l - (--l))] = abcd[1];
        System.out.println(new String(present)); // print: aaab -> aabb -> abbb -> bbbb
    }
    System.out.println(new String(word)); // print: bbbb

If i change this line(5): byte[] present=word;

to byte[] present=new byte[]{abcd[0],abcd[0],abcd[0],abcd[0]};

then I get the desired output. Why is this happening?

like image 441
satiate Avatar asked Nov 20 '25 18:11

satiate


1 Answers

present is being set to a reference to word. The values in word are not being copied. So when you change values in present, it's really changing the variable that present "refers" to: word.

like image 168
Michelle Avatar answered Nov 22 '25 06:11

Michelle



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!