0

I was asked to implement a swap method in java. I had no idea what that even was. So the interviewer gave me the below. And I totally bombed it with my implementation. could someone explain me the details of how and why this should be solved?

public class swapper {

    public static void main(String[] args) {

        String s1 = "first";
        String s2 = "second";

        System.out.println("First: " + s1);
        System.out.println("Second: " + s2);

        swap(s1, s2);

        System.out.println("First: " + s1);
        System.out.println("Second: " + s2);
    }

    public static void swap(String s1, String s2) {
        String[] myarr = new String[2];

        myarr[0] = s1;
        myarr[1] = s2;

        s2 = myarr[0];
        s1 = myarr[1];

    }
}
user836087
  • 2,271
  • 8
  • 23
  • 33
  • 2
    If you were to guess, what do you think a method named `swap` is supposed to do? – Robert Harvey Feb 08 '14 at 00:03
  • ummm.. Swap things. :) – user836087 Feb 08 '14 at 00:04
  • 2
    You can't do this in Java: http://stackoverflow.com/questions/3698323/swap-two-strings-in-java-by-passing-them-to-a-utility-function-but-without-ret Java passes references by value, so while you have a reference in the function and it swaps there, you didn't actually modify anything. I think your interview question was a trick one :) – devshorts Feb 08 '14 at 00:06
  • 1
    Looks like this is a very smart interviewer. He gave you a problem that's essentially unsolvable, and waited for you to tell him why. – Robert Harvey Feb 08 '14 at 00:11

0 Answers0