Alex O'Connor
Alex O'Connor

Reputation: 152

How to Test if a String Index is Null in Java

I'm getting "java.lang.NullPointerException" when I run the following code:

    while(StringName[PlaceString] != null){
      StringCounter = 0;
        while(StringCounter < StringName[PlaceString].length()){
          System.out.println("PlaceString: " + PlaceString + " PlaceLine: " 
          + PlaceLine + " Length of string: " + StringName[PlaceString].length());
          //Does stuff with string
    }}

The output is:

    PlaceString: 0 PlaceLine: 0 Length of string: 2
    Exception in thread "main" java.lang.NullPointerException

The root of the error is:

    while(StringCounter < StringName[PlaceString].length()){

although it runs the next line that prints variable's values. I can't figure out why it's complaining about a NullPointer when it can print their values.

Edit: Since I'm not getting a java.lang.StringIndexOutOfBoundsException, the question:

Java substring : string index out of range

didn't help.

Upvotes: 0

Views: 832

Answers (1)

davidxxx
davidxxx

Reputation: 131346

You don't show all the relevant code but according to the exception and its location, you set very probably the value of PlaceString during the inner while :

while(StringCounter < StringName[PlaceString].length()){
      System.out.println("PlaceString: " + PlaceString + " PlaceLine: " 
      + PlaceLine + " Length of string: " + StringName[PlaceString].length());
      //Does stuff with string
       StringCounter++; // or something close
}

At a certain iteration, StringName[PlaceString] refers to a null element.
So the NPE is thrown.

The outer while will not help here :

while(StringName[PlaceString] != null){

as it is not executed before the inner loop terminates its iterations.

So you could avoid the NPE by adding the guard in the inner while :

while(StringName[PlaceString] != null && StringCounter < StringName[PlaceString].length()){
      System.out.println("PlaceString: " + PlaceString + " PlaceLine: " 
      + PlaceLine + " Length of string: " + StringName[PlaceString].length());
      //Does stuff with string
}

Upvotes: 3

Related Questions