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].
originalandswitchedreference the same array. Anything you do to one of them you're doing to both. You want a new array.