-1

Please find the error in my code

  public int longestkSubstr(String s, int k) {
    // code here
    if(s.length()==0)
    return 0;
    int i=0,j=0;
    int ans=-1;
    Map<Character,Integer> map=new HashMap<>(); 
    while(j<s.length()){
        map.put(s.charAt(j),map.getOrDefault(s.charAt(i),0)+1);
       
        if(map.size()<k)
        j++;
        else if(map.size()==k){
        ans=Math.max(ans,j-i+1);
        j++;
        }
        else if (map.size()>k){
          
        while(map.size()>k){
            
            map.put(s.charAt(i),map.get(s.charAt(i))-1);
            if(map.get(s.charAt(i))==0)
            map.remove(s.charAt(i));
        i++;
     } j++;}   
}
return ans;`}

Runtime Error: Runtime ErrorException in thread "main" java.lang.NullPointerException at Solution.longestkSubstr(File.java:43)

  • 2
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – maloomeister Jul 02 '21 at 06:06
  • 1
    We can only guess here, since you only posted the method where the exception occurs, but now how you call this method. You also didn't provide the information _what line_ line 43 in `longestkSubstr` is. The best thing for you to do is to learn how to use a debugger, to step through your code and find out what exactly is null (and why). Are you sure that `s` is not null? – maloomeister Jul 02 '21 at 06:12

1 Answers1

0
Map<Character, Integer> map = new HashMap<>();

Here you've declared Map as <Character, Integer>. Integer type object's value can be null.

map.put(s.charAt(i),map.get(s.charAt(i))-1);

Here in "map.get(s.charAt(i))-1", even when map.get(s.charAt(i)) is returning NULL, your code is still trying to perform arithmatic opearation on that.

This is the reason for showing java.lang.NullPointerException.

Map.get() returns null when the key is not present. An Integer (autoboxed type) that is null can not be autounboxed into an int, so it throws NullPointerException.

Note: Java uses autoboxing to convert Integer to int

Solution:

Anywhere you use map.get, try to keep a check whether it's null or not.

In your case it might be like following,

if( map.get(s.charAt(i)) != null) map.put(s.charAt(i), map.get(ch) - 1);
if (map.get(s.charAt(i)) != null && map.get(s.charAt(i)) == 0)

Please check following reference to know more about get() method and other uses of Map

Happy coding!

Md. Faisal Habib
  • 1,014
  • 1
  • 6
  • 14