Occurrence of character in a given String in java [Best Program]

Occurrence of character in a given String in java: In Java, you can use the charAt() method of the String class to get the character at a specific index in the string. Then you can loop through the string to count the number of occurrences of a specific character.

Here’s an example code snippet that counts the number of occurrences of the character ‘a’ in a given string:

Occurrence of character in a given String

String str = "Hello world!";
char searchChar = 'a';
int count = 0;

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

System.out.println("The character '" + searchChar + "' appears " + count + " times in the string.");

In this example, we first define the input string str and the character we want to search for searchChar. We also initialize a variable count to 0 to keep track of the number of occurrences.

We then use a for loop to iterate through each character in the string. For each character, we check if it is equal to the search character. If it is, we increment the count variable.

Finally, we print out the result which tells us how many times the character appeared in the string.

Count Occurrences of each character in string java using stream

In Java, you can also count the occurrences of each character in a string using the chars() method of the String class to convert the string to an IntStream of character codes. Then you can use the collect() method with a groupingBy() collector to group the character codes by their frequency.

Here’s an example code snippet that counts the number of occurrences of each character in a given string using a stream:

String str = "Hello world!";
Map<Character, Long> charFrequency = str.chars()
        .mapToObj(c -> (char) c)
        .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

System.out.println("The frequency of each character in the string:");
charFrequency.forEach((key, value) -> System.out.println(key + ": " + value));

In this example, we first define the input string str. We then use the chars() method to convert the string to an IntStream of character codes. Occurrence of character in a given String

We then use the mapToObj() method to map each character code back to its corresponding character. This gives us an Stream<Character>.

We then use the collect() method with a groupingBy() collector to group the characters by their frequency. The groupingBy() collector creates a map where the keys are the characters and the values are the number of times each character appears in the string.

Finally, we print out the result which tells us the frequency of each character in the string. We use the forEach() method to iterate over the entries in the map and print out the key (character) and value (frequency) for each entry. Occurrence of character in a given String

Find Occurrence of Maximum Character in a given string

To find the maximum occurring character in a given string in Java, you can use a similar approach as in the previous answer. Here’s an example code snippet:

public static void maxCharOccurrence(String str) {
    // Step 1: Create an empty HashMap to store the frequency of each character in the string
    Map<Character, Integer> charFreq = new HashMap<>();

    // Step 2: Loop through each character in the string
    for (char c : str.toCharArray()) {
        // Increment the frequency count in the HashMap for that character
        charFreq.put(c, charFreq.getOrDefault(c, 0) + 1);
    }

    // Step 3: Find the maximum value in the HashMap
    int maxFreq = Collections.max(charFreq.values());

    // Step 4: Loop through the HashMap again and print out the keys that have the same value as the maximum value
    for (Map.Entry<Character, Integer> entry : charFreq.entrySet()) {
        if (entry.getValue() == maxFreq) {
            System.out.println(entry.getKey() + ": " + entry.getValue() + " occurrences");
        }
    }
}

In this example, the maxCharOccurrence function takes a string as input and prints the character(s) with the maximum frequency in the string. The function uses a HashMap to store the frequency of each character in the string, and then finds the maximum value in the HashMap using the Collections.max method. Finally, the function loops through the HashMap again and prints out the keys that have the same value as the maximum value. Occurrence of character in a given String

To find the maximum occurring character in a given string in Java, you can use a HashMap to keep track of the frequency of each character in the string. Here’s an example code snippet: Occurrence of character in a given String

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "hello world";
        Map<Character, Integer> charFreqMap = new HashMap<>();
        
        // Count the frequency of each character in the string
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            charFreqMap.put(c, charFreqMap.getOrDefault(c, 0) + 1);
        }
        
        // Find the character with the maximum frequency
        char maxChar = '\0';  // null character
        int maxFreq = 0;
        for (Map.Entry<Character, Integer> entry : charFreqMap.entrySet()) {
            char c = entry.getKey();
            int freq = entry.getValue();
            if (freq > maxFreq) {
                maxChar = c;
                maxFreq = freq;
            }
        }
        
        // Print the result
        System.out.println("The maximum occurring character in the string \"" + str + "\" is '" + maxChar + "' with frequency " + maxFreq);
    }
}

In this code, we first create a HashMap charFreqMap to store the frequency of each character in the string. We then iterate through each character in the string and update the frequency in the map.

After counting the frequency, we iterate through the map to find the character with the maximum frequency. We use a variable maxChar to keep track of the character with the maximum frequency, and a variable maxFreq to keep track of the maximum frequency seen so far. We update these variables if we find a character with a higher frequency.

Finally, we print out the character with the maximum frequency and its frequency.

String Program in java for interview

Here’s an example Java program that demonstrates some string operations:

public class StringDemo {
    public static void main(String[] args) {
        String str1 = "Hello, World!";
        String str2 = "hello, world!";
        
        // length of the string
        int len1 = str1.length();
        int len2 = str2.length();
        System.out.println("Length of str1: " + len1);
        System.out.println("Length of str2: " + len2);
        
        // concatenation of two strings
        String str3 = str1 + " " + str2;
        System.out.println("Concatenated string: " + str3);
        
        // substring of a string
        String subStr1 = str1.substring(0, 5);
        String subStr2 = str2.substring(0, 5);
        System.out.println("Substring of str1: " + subStr1);
        System.out.println("Substring of str2: " + subStr2);
        
        // comparison of two strings (case-insensitive)
        boolean equalsIgnoreCase = str1.equalsIgnoreCase(str2);
        System.out.println("str1 equalsIgnoreCase str2: " + equalsIgnoreCase);
        
        // replace a character in a string
        String replacedStr1 = str1.replace('o', 'x');
        String replacedStr2 = str2.replace('o', 'x');
        System.out.println("Replaced string of str1: " + replacedStr1);
        System.out.println("Replaced string of str2: " + replacedStr2);
        
        // convert a string to uppercase and lowercase
        String upperCaseStr1 = str1.toUpperCase();
        String lowerCaseStr2 = str2.toLowerCase();
        System.out.println("Uppercase string of str1: " + upperCaseStr1);
        System.out.println("Lowercase string of str2: " + lowerCaseStr2);
    }
}

This program demonstrates various string operations like finding the length of a string, concatenating two strings, extracting a substring, comparing two strings (case-insensitive), replacing a character in a string, and converting a string to uppercase and lowercase. These are some of the commonly used string operations in Java, and can be useful in interviews for demonstrating your familiarity with the language.

String Important Program Questions

Here are some important String program questions that might be asked in an interview:

  1. Write a program to find the length of a string in Java.
  2. Write a program to reverse a string in Java.
  3. Write a program to check if a string is palindrome or not in Java.
  4. Write a program to count the occurrences of a character in a string in Java.
  5. Write a program to find the first non-repeated character in a string in Java.
  6. Write a program to check if two strings are anagrams or not in Java.
  7. Write a program to remove all white spaces from a string in Java.
  8. Write a program to check if a string contains only digits in Java.
  9. Write a program to find the second highest occurrence of a character in a string in Java.
  10. Write a program to count the number of words in a string in Java.

These are just a few examples of the types of string programs that might be asked in an interview. Make sure to practice these programs and understand the underlying concepts to prepare for your interview.

Join TelegramJoin Now
Home PageFull Stack With Java
Occurrence of character in a given String

Leave a Comment