-2

Hi I am working in string array and It seeming wont add the data in the array keep me getting an error or null exception

public boolean addCategory(String description){
if(numCategories <= maxArrayCategories){
    arrayCategories[numCategories] = description;
    numCategories++;
    return true;}
else {return false;}}

Is the problem the function?

3 Answers3

5

arrayCategories is null, you need to create the array itself in order to use it:

arrayCategories = new String[maxArrayCategories];

Somewhere at the top of your code, if this is a class member, probably in the constructor.

In Java null is a language literal meaning that the reference (in this case your array) point to nowhere. A NullReferenceException means you are trying to access a value that has not been initialized yet, or was set explicitly to null (In this case, you are trying to set an array cell, where the array has not been initialized yet).

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0

The problem with your code is that you have never initialized arrayCategories array.That's why it is throwing NullPointerException. You must initialize an array before using it. For example if you already knowing that the arrayCategories is going to have maxArrayCategories number of elements then you should initialize the array before calling the method addCategory using:

arrayCategories = new String[maxArrayCategories];

And also make sure that the condition to be checked should be

if(numCategories < maxArrayCategories)
Vishal K
  • 12,976
  • 2
  • 27
  • 38
0
//Hi I hope numCategories is like a index and has value 0 and maxArrayCategories is the length of array and hope you have initialized the array arrayCategories then please try this.
//it would be work.

public boolean addCategory(String description){
if(numCategories < maxArrayCategories-1){
    arrayCategories[numCategories] = description;
    numCategories++;
    return true;}
else {return false;}}