Search code examples
javaarraysmethodsprogram-entry-pointswap

A method that swaps places between two indexes in an array


I have just created a method that is supposed to swap places between index[0] and index[1] in an array.

However I can't seem to find how i should return this to the main method and then print it out in the swapped order.

What did I do wrong?

public class Uppgift4_6a {
    public static void main(String[] args) {
        int [] intArray= new int [] {2, 4};
        int l= intArray[0];
        int r= intArray[1];
        System.out.println("right order:" + l + " " + r);
        exchange(intArray, intArray[0], intArray[1]);
        System.out.println("right order:" + l + " " + r);
    }

    public static void exchange (int[] intArray, int l, int r){
        l = intArray[0]; 
        r = intArray[1];
        intArray[1] = l;
        intArray[0] = r;
        return;
    }
}

Solution

  • Why do you want to return something ? The array will be updated, as you're passing a reference to an object. However, l and r will not be updated.

    Just print out like this

    System.out.println("right order:" + l + " " + r);
    exchange(intArray, intArray[0], intArray[1]);
    System.out.println("right order:" + intArray[0] + " " + intArray[1]);