0

I am confused with something about String arrays. If I change the array in a method and access it within the method, it stays changed, but if I use the method to change it, then access it right after, it doesn't work.

public class ArrayTester{

    public static void main(String[] args){
            String[] names = {"Jim", "Gary", "Bob"};
            printMe(names);
            remove(1, names);
            printMe(names);

    }


    printMe(String[] array){
            for(String str : array){
                System.out.print(str + " "); 
            }
            System.out.println();
    }

    remove(int pos, String[] array){
            array2 = new String[array.length - 1];
            for(int i = 0; i < pos; i++){
                array2[i] = array[i];
            }
            for(int i = pos; i < array2.length - 1; i++){
                array2[i] = array[i + 1];
            }
            array = array2;
            //printMe(array); <-- works with printMe here, but not in the 
            //                    main method
    }

}

I expect the result to look like "Jim Gary Bob" and then "Jim Bob" Unfortunately, I get "Jim Gary Bob" twice. However, if I put printMe in the remove method instead of in the main method, I get "Jim Gary Bob" and then "Jim Bob" I'm not sure why it is and I suspect it's got something to do with the way the array is stored, but I can't figure it out.

  • 1
    Because you never modified `names` in your `main` method. Your `remove` method creates a *new* array and modifies *that*. Did you mean to *return* that new array and set that return value to `names`? – David Dec 11 '17 at 18:22
  • Please, post code that doesn't contain compile errors. You forgot the return types for the printMe() and remove() methods. – Ralf Kleberhoff Dec 11 '17 at 19:59

0 Answers0