java.lang.NullPointerException at String.indexOf

The String.indexOf method return the index of the first occurrence of the matched string.If the matched string is passed as first parameter of String.indexOf method. If the matched string is null, NullPointerException is thrown by this method.

The NullPointerException is thrown in the below String methods

  • String.contains
  • String.replace
  • String.format – If the format is null
Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.indexOf(String.java:1718)
	at java.lang.String.indexOf(String.java:1698)
	at com.yawintutor.StringIndexOf.main(StringIndexOf.java:9)


Root Cause

The first parameter of the String.indexOf method is used to match with the given string. If the matched string is null, then index can’t be found.



Solution

Make sure the first parameter of the String.indexOf method contains an empty string or a not null String.

package com.yawintutor;

public class StringIndexOf {
	public static void main(String[] args) {
		String str = "Yawin";
		String str2 = "win";
		int index;

		index = str.indexOf(str2);

		System.out.println("Given String : " + str);
		System.out.println("String index : " + index);
	}
}

Output

Given String : Yawin
String index : 2



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *