Write a Java method to count all the words in a string.

Source Code:

public class CountWords {
public static void main(String[] args) {
int result = countWords(“Java is very easy”);
System.out.println(result);
}

public static int countWords(String str) {
String[] words = str.trim().split(“\s+”);
return words.length;
}
}

Output: