Is indexOf() in String class expensive operation? Because I imagine for example if a String has length 1000 and the last character is "a". And I need to find an "a" in the String, it will go one by one until the 1000th character until it finds "a".
Is it better to user JAVA Regular Expression in all cases?
You could run some tests and find out for yourself. But I can't imagine how a regular expression that simply searched for an "a" in a String could avoid looking at all the characters that the indexOf() method would look at. If anything I would expect the regex would be slower, because of the setup processing.
In practice, indexOf() uses a fairly simple nested loop to search for the target string, while Pattern uses some more complicated, sophisticated techniques - including one called the Boyer-Moore algorithm. This means that for strings which are longer than length 1, Pattern may be able to give significantly faster searches than indexOf(). I think this would be true especially if both the target and input strings are large - the larger they are, the more benefit you get from Boyer-Moore and Pattern. However for short targets and especially for short input, Pattern has more overhead, and indexOf() will be faster. I encourage you to measure some sample times for various scenarios if this interests you. [ October 03, 2007: Message edited by: Jim Yingst ]