0

Can I initialize an instance variable in Java, when I initialise it when I declare it, and initialise it with the return value of a method, which I define later in the class.

Something like this:

public class MyClass {

     integers[] myArray = new integers[length()];

     int length() {
     ....

     }
}

length() gives me some number, and I want this number to determine the number of elements in the array. It seems plausible to me, but I get NullPointerException (I don't know whether this mistake initialization is causing the exception, but I don't know what exactly, and because I have never done this initialization before, I am not sure it is correct).

4 Answers 4

3

Seems to work fine for me, with the method static or not static:

public class test
{
    public int[] myarray = new int[this.length()];

    public int length() {
        return 5;
    }

    public static void main(String[] args)
    {
        test foo = new test();
        for (int element : foo.myarray) {
            System.out.println(element);
        }
    }
}

Which produces:

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

Comments

2

Before doing this, it might be worth considering if this syntax might be slightly confusing, and that it might be more appropriate to initialize the array in the constructor, or in an initialization block.

private final int[] myArray;

public MyClass() {
    myArray = new int[length()];
}

or

private final int[] myArray;
{
    myArray = new int[length()];
}

Comments

2

Chances are the problem is somewhere in the length() method. I suspect it refers to a variable which hasn't been appropriately initialized yet. Here's an example of a program which shows that:

public class MyClass {

    int[] myArray = new int[length()];

    // This is only initialized *after* myArray
    String myString = "Hi";

    int length() {
        return myString.length();
    }

    public static void main(String[] args) {
        new MyClass(); // Bang!
    }
}

If this is the problem, I suggest you do the initialization within the constructor instead - that way the ordering is much clearer.

1 Comment

+1. this problem is discussed extensively in effective java java.sun.com/docs/books/effective.
-3

You have to make the method static:

static int length() { … }

Comments

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.