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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With