Search code examples
javaarraysinstance-variables

Assign a value to a String variable in a String array


I am trying to assign values to String variables within an array:

String details = "passFirst0,passLast0,Molly,Quinn";
Passenger passenger = new Passenger(details);

public class Passenger {

    private String firstNameField;
    private String lastNameField;
    private String firstName;
    private String lastName;

    public Passenger(String details) {
        String[] temp = details.split(",");
        String[] fields = {firstNameField, lastNameField, firstName, lastName};

        for (int ctr = 0; ctr < fields.length; ctr++) {
            fields[ctr] = temp[ctr];
        }

        // Print instance variables - all null
        System.out.println(this.firstNameField);
        System.out.println(this.lastNameField);
        System.out.println(this.firstName);
        System.out.println(this.lastName);

        // Print array - has values
        System.out.println(Arrays.toString(fields));
    }

    // Methods
}

However, the instance variables themselves remain null, while the fields[] has values when you iterate through the array.

Why is this so and how to accomplish this?


Solution

  • String objects are immutable - you cannot change their value - while doing assignments you are changing object to which the variable (or variable at given array index) is referring to.

    When you do:

    String[] fields = {firstNameField, lastNameField, firstName, lastName};
    

    you set reference of fields array value with index 0 to same object that firstNameField is referring to (in this case null), index 1 to refer to same object as lastNameField, etc.

    Then, if you do:

    fields[ctr] = temp[ctr];
    

    you are not changing value of the object fields[ctr] was referring earlier (one of your instance variables) to value of temp[ctr], but rather you are setting fields[ctr] to refer to the same object temp[ctr] is referring to right now.

    If you want to refer to your variables as an array, why won't you just declare them as an array from the beginning?