0

I was trying to make a short code to switch the first and last values in an array and output a new array identical to the first array but with those values switched. After trying a few times, I realized my first (original) array kept switching its [0] value, and I can't tell why. This is the code.

import java.util.Arrays;
public class testing {
    public static void main(String[] args) {
       int[] original={1,2,3,4};
       int[] switched=original;
       switched[0]=original[original.length-1];
       switched[switched.length-1]=original[0];
       System.out.println(Arrays.toString(switched));

}

}

I wanted the output to be [4,2,3,1], but I always get [4,2,3,4].

1
  • 3
    Both original and switched reference the same array. Anything you do to one of them you're doing to both. You want a new array. Commented Feb 27, 2014 at 1:03

3 Answers 3

1

both are reference to same array

initially

1,2,3,4

after

switched[0]=original[original.length-1];

4,2,3,4

after

switched[switched.length-1]=original[0];

4,2,3,4
Sign up to request clarification or add additional context in comments.

Comments

0

There is some magic you should know :).

In this line : int[] original={1,2,3,4}; you create array {1,2,3,4} and you store REFERENCE to it in your variable original

In this line : int[] switched=original; you copy the value of original which is REFERENCE to that array into the variable switched.

Now, you have two variables which are both referencing to the same array!


To create new array with same values, you can use this :

int [] switched = (int[])original.clone();

Comments

0

Because switched and original pointing to the same object.

Do:

import java.util.Arrays;
public class testing {
    public static void main(String[] args) {
        int[] original={1,2,3,4};
        int[] switched={1,2,3,4};
        switched[0]=original[original.length-1];
        switched[switched.length-1]=original[0];
       System.out.println(Arrays.toString(switched));
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.