0

If I create an array of variables:

public String a;
public String b;
public String c;

public String[] d = {a,b,c};

it will contain {null, null, null};

If I then do this:

a = "5";
System.out.println(d[0]);

output will be null since a was null when d was initialised.

Is there a way to create an "array of references", so that output in this case would be 5?

EDIT: PLOT TWIST!

First part of code is in some class. Second part is in a class that is extending the first one.

4
  • 2
    How are you getting null from primitives? Also, those variables haven't been initialized; the code won't compile. Commented Nov 23, 2013 at 19:19
  • 3
    "it will contain {null, null, null};" No your code won't compile. Commented Nov 23, 2013 at 19:19
  • 1
    Output will not be null, it will be zero (0), because primitives integers are initialized to zero. Use the object wrappers (Integer). Commented Nov 23, 2013 at 19:20
  • OKay, my bad, I tried to simplify it too much. I was using Strings... Commented Nov 23, 2013 at 19:21

1 Answer 1

1

You can wrap the Strings with your own mutable class:

class MyString {
    private String value;

    public MyString(String value) {
        this.value = value;
    }

    void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
       return value;
    }
}

Now:

public MyString a = new MyString(null);
public MyString b = new MyString(null);
public MyString c = new MyString(null);

public MyString[] d = {a,b,c};

...

a.setValue("5");  // <--

You might want to ensure that a is not null before calling setValue(), however.

Sign up to request clarification or add additional context in comments.

2 Comments

@MarkoTopolnik Why do they need explicit initialization? They're fields, not local variables.
Because a.setValue("5") results in an NPE as you have showed it, and d is still {null, null, null}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.