user985206
user985206

Reputation: 11

Why do i get the NullPointerException error with my array?

My program runs. Its just that in the middle of the program it says:

Exception in thread "main" java.lang.NullPointerException
at Example.main(Example.java:33)

Here is my code:

String [] iArray ;
String i ;
int counter=1 ; counteragain=-1, q;

do {
System.out.print ("\n\nItem Code : ") ;
i = s.next();

if (i.equals ("0") ){
  counter = 0 ;
} else {
  System.out.print ("\nQuantity: ") ;
q = s.nextInt() ;
counteragain++ ;

i = iArray[counteragain];
}
} while (counter!=0) ;

The line where I'm getting the error is:

 i = iArray[counteragain];

Why do I get this error? Is my syntax wrong? But then why does it run my program?

Any help would be much appreciated.

Upvotes: 0

Views: 213

Answers (6)

Brett Walker
Brett Walker

Reputation: 3576

iArray is never initialized. So the dereferenced iArray[counteragain] does so with a null reference; hence the NullPointerException.

Upvotes: 0

Ajitabh Shetty
Ajitabh Shetty

Reputation: 1

iArray = new String[n];, where n is the number of elements in iArray.

Should help you get rid of NullPointerException..

Upvotes: 0

Giovanni
Giovanni

Reputation: 4015

Your code is not complete, it does not show what s is (I guess it is an iterator) and where it came from. From the code you posted the Exception is the consequence of

String [] iArray;

You did not initialize iArray so it's null; you should post a working method/class in order to get the correct answer.

Upvotes: 0

Boaz
Boaz

Reputation: 4669

you need to allocate the array. the line String [] iArray ; only declared a reference to an array of type string but did not allocate any room for objects in the array; you need to change that line to something like

String[] iArray = new String[size of needed array];

if you cant predict the needed size, it might be better to use a collection type like ArrayList

Upvotes: 0

eversor
eversor

Reputation: 3073

You did not initialize this Array. Therefore it has a null value. You have to do something like this

String[] iArray = new String[numberOfElements];

You do not need to initialize the array in the declaration. So you can first recollect this numberOfElements and then initialize it.

iArray = new String[numberOfElements];

Upvotes: 3

Buhake Sindi
Buhake Sindi

Reputation: 89169

String [] iArray ; is never instantiated. So, initially, iArray is null.

When you're getting an element i = iArray[counteragain];, you're trying to access an uninstantiated array, so a NullPointerException is thrown.

I don't know what's your array size, but to un-nullify it, you will have to do:

String[] iArray = new String[size];

Now, iArray will have a placeholder of length size but each element will be null as it hasn't been assigned a value. i.e., iArray[0] will be null as there is no value at element 0.

Upvotes: 2

Related Questions