You can count words in Java String by using the split() method of String. A word is nothing but a non-space character in String, which is separated by one or multiple spaces. By using regular expression to find spaces and split on them will give you an array of all words in given String. This was the easy way to solve this problem as shown here, but if you have been asked to write a program to count a number of words in given String in Java without using any of String utility methods like String.split() or StringTokenizer then it's a little bit challenging for a beginner programmer. It's actually one of the common Java coding questions and I have seen it a couple of times with Java developer interviews of 2 to 4 years of experience. The interviewer put additional constraints like split() is not allowed, you can only use basic methods like charAt(), length(), and substring() along with loop, operators, and other basic programming tools.
Read more »