Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modifying elements within an array

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"}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading