Null pointer access: The variable can only be null at this location
Asked Answered
G

1

5
for(int i=0;i<n;i++){
  for(int j=0;j<26;j++){
    if(str.charAt(i)== strChar.charAt(j) )
    * strSet1.append(str.charAt(i));
  }
    * strSet2.append(str.charAt(i));
}

Exception:

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

why this code gives null pointer exception

warning: Null pointer access: The variable strSet1 can only be null at this location Null pointer access: The variable strSet2 can only be null at this location

Grondin answered 17/11, 2013 at 19:30 Comment(5)
Please provide the entire warning message, and mark the line where it's occurring.Jollenta
this means the length of your str string is less than either n or 26Felker
I think your inner loop condition isn't right. what is your string length?Ferrick
@TusharGupta: In that case it would throw IndexOutOfBoundsException. NPE is thrown when you call a method on a null object for instance.Beaujolais
str is n which is input and strChar is 26 alphabatesGrondin
B
8

Are strSet1 and strSet2 initialized before this? If they are null, you'd get a NullPointerException.

* EDIT *

You cannot call .append() (or any other method) on a variable that is null. Initialize them as:

StringBuffer strSet1 = new StringBuffer();
StringBuffer strSet2 = new StringBuffer();
Beaujolais answered 17/11, 2013 at 20:15 Comment(7)
initially Yes, all three variable are initialize with null, so what should i do? @tomppaGrondin
See updated answer, you cannot call methods on null objects.Beaujolais
latter str contains input and strChar is not null-it contains 26 alhabates @tomppaGrondin
What about strSet1 and strSet2?Beaujolais
of course, str is less than 26 but str String is equal to n @Tusar guptaGrondin
strSet1 and strSet2 is BufferString with null -- @tomppaGrondin
Thus you can fix the program by initializing them like shown above (edited answer again).Beaujolais

© 2022 - 2024 — McMap. All rights reserved.