1

I am trying to access an array that is part of an object.

I am getting the error "Exception in thread "main" java.lang.NullPointerException at OrderedStringList.add(OrderedStringList.java:21) at Main.main(Main.java:24)"

I have cut my program down to the bare bones, cutting out everything that might be interfering with the output.

public class Main {

public static void main(String[] args) {

    int x = 5;

    OrderedStringList myList = new OrderedStringList();

    myList.add(x);
    }
} //end class

This code references the class OrderedStringList.

public class OrderedStringList {

public int values[];

OrderedStringList(){
    int values[] = new int[5];
}

public void add(int y) {
    values[0] = y;
    System.out.print(values[0]);
}

I assume that the numbers 21 and 24 in the error are line numbers. Because I have some things commented out in my original code, the code I have posted would normally have some content in the middle of it. Line 24 in main is: myList.add(x);. Line 21 of OrderedStringList is: values[0] = y;.

I'm guessing that there is something really simple that I am missing. Anything is appreciated.

Thanks.

2
  • 1
    Main.java:24 and OrderedStringList.java:21 do indeed point to the class and line number you're having the error at. Commented Sep 27, 2013 at 0:41
  • In your constructor, int values[] = new int[5]; declares a local variable values! Note, your compiler should have warned you about this unused variable. Commented Sep 27, 2013 at 0:59

4 Answers 4

5

Here

OrderedStringList(){
    int values[] = new int[5];
}

You shadow the class member values.

Change this to:

OrderedStringList(){
    values = new int[5];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! it's been several months since I worked with java and I guess I was rustier than I thought. Greatly Appreciated.
2

You've declared values twice....

public int values[];

OrderedStringList(){
    int values[] = new int[5];
}

This commonly known as shadowing.

Change the initialization of the array in the constructor to something like...

public int values[];

OrderedStringList(){
    value = new int[5];
}

Instead...

Comments

2

This declares the values[] array just inside the scope of the method.

OrderedStringList(){
    int values[] = new int[5];
}

If want to refer to the Class scope use

OrderedStringList(){
    values = new int[5];
}

1 Comment

:-) Sorry, have just seen a lot of unbelievable "answers" tonight
1

With the line int values[] = new int[5];, you're declaring an entirely new int[] that exists only in the constructor. Change it to values = new int[5];.

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.