Java - Write code to count Occurrences of a char inside a string

Requirements

Write code to count Occurrences

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String haystack = "book2s.com";
        char needle = 'o';
        System.out.println(countOccurrences(haystack, needle));
    }/*from  w  ww. java2 s .c o  m*/

    public static int countOccurrences(String haystack, char needle) {
        int count = 0;

        for (int i = 0; i < haystack.length(); i++) {
            if (haystack.charAt(i) == needle) {
                count++;
            }
        }

        return count;
    }
}