Skip to main content

Posts

Showing posts from April, 2012

contains() and indexOf() in Java will return true for Empty String("")

In Java we will use String.contains(String2) to check a String contains another String. This Contains() method will return true if we String2 is empty that means "". Also String.indexOf(String2) and String2 is empty "", this also will return 0. If we check return index is greater than -1 or not equal to -1, this will return true. So to avoid this, we have to check the given string is not empty.                 String s = ""; String b = "test"; System.out.println("b contains s?:"+b.contains(s)); //true System.out.println("b indexOf s?:"+b.indexOf(s)); //0 System.out.println("b indexof 't'?:"+b.indexOf("t")); //0 System.out.println("s contains b?:"+s.contains(b)); //false Do not check index or contains for empty String at any time.