1

I have an array initialized and filled up, but I can not access its values in any other methods than the one it is filled in. If I try to work with it in other methods I get a nullPointerException. For example if I say "System.out.println(board[2][2])" inside the init methos it works but in another method throws nullPointerException. I have been trying for hours to figure it out but have no idea what's wrong? Can anybody shine some light on my problem? It would be much appreciated. Thanks

public class Program2 extends JPanel implements ActionListener 
{
    private LifeCell[][] board;   
    private JButton next;          
    private JFrame frame; 

    public static void main(String[] args) {new Program2();}

    public Program2()
        {
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(this);
            this.init();
            frame.pack();
            frame.setVisible(true);
        }

            public void init()
            {
                LifeCell[][] board = new LifeCell[10][10];
                this.setPreferredSize(new Dimension(400, 500));
                this.setLayout(null);

                for (int r = 0; r < 10; r++)
                {
                    for (int c = 0; c < 10; c++)
                    { 
                        board[r][c] = new LifeCell(board, r, c);
                        this.add(board[r][c]);
                        board[r][c].setBounds(x,y,40,40);
                        this.setVisible(true);


                        System.out.println(board[2][2]) //works
                    }
                }
             }
        public void test(){ System.out.println(board[2][2])}//doesn't work
}
1
  • Question is already sufficiently answered but I'd like to add that you might want to configure you IDE so that it helps you find such problems. E.g. eclipse supports this: Preferences -> Java -> Java Compiler -> Errors/Warnings then turn on 'Local variable declaration hides another field or variable'. Commented Nov 13, 2013 at 22:08

5 Answers 5

5
LifeCell[][] board = new LifeCell[10][10];

should be

board = new LifeCell[10][10];

By redefining it as LifeCell[][] inside the init() method, you're creating a new variable board which scope is limited to that method. Afterwards you try to print the board array that's in the class scope (and uninitialized) which gives you the errors you're having.

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

4 Comments

Thank you so much! All that time I spent trying different things and that little mistake I made was it. You're awesome!
One heuristic that may help you notice this type of error in the future, is to always refer to instance variables (a.k.a. non-static fields) as this.board. That way you don't need to rely on syntax highlighting, or memorization to notice the difference between instance and local variables. Use Program2.myField to refer to a class variable (a.k.a. static field). See docs.oracle.com/javase/tutorial/java/nutsandbolts/… for the definitions of the various variable types.
If you have that many local variables in your method that would cause you to lose track of locals vs instances, you're doing something wrong.
Don't need to be rude, I'm new to programming.
3

In java you can have a local variable, and an instance variable with the same name. The order of precedence though is to check for a local variable with the name first, and then an instance variable after if the local version is not present(1), unless specified with this.

What is happening here, is rather than initializing the instance copy of "board" you're creating a new board, but only locally to init(). The rest of your class does not see it.

board = new LifeCell[10][10];

just remove the type declaration to the left of board, and it should know to assign it to the instance variable. To be more explicit you could say this.board = ...

  1. This sounds as though it's a performance hit, but these checks are all done at compile time, and will not effect runtime performance at all.

Comments

2

In init it should be:

board = new LifeCell[10][10];

With LifeCell[][] board = new LifeCell[10][10];you're declaring and instancing a new local variable with scope restricted to init method.

Comments

1

Thats because variables declared inside methods are local variables and they are not available in any other method than within they were declared. To acces in in your second method you have to pass it as a method argument, or simply declare your array as class' field. It will be available in every method in such class. As I can see you already deckared such field, however you are covering it with local variable by deckaring local with same name as field.

Comments

1

LifeCell[][] board = new LifeCell[10][10]; indicates that you are creating an object of type LifeCell array and assigning it to a NEW LOCAL variable board.Note that at this point the instance variable board is still null. When you do System.out.println(board[2][2]) inside the init method, the local variable is used(since it was declared in the same method). When trying to print values in test() method, the instance variable board is used which is still null.

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.