Using a custom loop
This is a conventional solution of finding a character count in the string. Here, we are using a loop to traverse each character of the string and comparing character by using the charAt()
method that returns a character present at the specified index and finally counting if a character matches the desired character.
public class CharOccurrence {
public static void main(String[] args){
String str = "abracadabra-banana";
System.out.println(str);
// count occurrence
int count = 0;
for (int i=0; i < str.length(); i++)
{
if (str.charAt(i) == 'a')
{
count++;
}
}
System.out.println("occurrence of a: "+count);
}
}
Save and close the file. Compile the Java program with the following command:
javac CharOccurrence.java
Execute the Java program with the following command:
java CharOccurrence