I dont get why this question’s answer is BABA according to kira learning and BBBB when i throw into w3schools. According to my own calculations, i got ABBA. According to java visualizer, w3schools and chatgpt, they changed both ab and ba to {"B", "B"} which does not make sense to me.
My working:
ba[0] = "A", which changes to ab[1] (B). ba = {"B", B"}
ba[1] = "B", which changes to ab[0] (A). ba = {"B", "A"}
ab = {"A","B"}
ba = {"B", "A"}
ab[0] + ab[1] + ba[0] + ba[1] = ABBA
Enlighten me on where I have gone wrong, I am a beginner at java. The question goes like this:
String[] ab = {"A", "B"};
String[] ba = ab;
ba[0] = ab[1];
ba[1] = ab[0];
System.out.println(ab[0] + ab[1] + ba[0] + ba[1]);
>Solution :
You didn’t copy the array to ba, but you made a reference. Changing the content of one changes it for both.
ba[0] = ab[1];
// ab[0] is now also set to ab[1], so ab[0] is B and ab[1] is B
ba[1] = ab[0];
// ab[1] is now also set to ab[0]
To achieve what you expect, use Array.clone():
String[] ab = {"A", "B"};
String[] ba = ab.clone();
ba[0] = ab[1];
ba[1] = ab[0];
System.out.println(ab[0] + ab[1] + ba[0] + ba[1]);