This post will discuss how to check if a specific character appears in a String in Java.

To check if a specific character appears in a string in Java, we can use one of the following methods:

1. Using String.indexOf() method

A simple solution is to use the indexOf() method of the String class. This method returns the index of the first occurence of the specified character within a string, or -1 if no such character occurs. We can compare its return value against -1 to determine if the specific character appears in the string. For example, to check if the character 'a' appears in the string "Java", we can write:

Download  Run Code

2. Using String.contains() method

Another option is to use the contains() method of the String class. This method checks if the string contains a specified sequence of characters. This method returns true if the sequence is present, otherwise false. Since the contains() method accepts the string sequence to search for, to check if a single character appears in a string, we need to convert the character to a string first using the String.valueOf() method. Here is a sample code that demonstrates this:

Download  Run Code

3. Using regular expressions

A regular expression is a sequence of characters that defines a search pattern. We can use the matches() method of the String class to check if a string matches a given regular expression. To check if a specific character appears in a string, we can use a character class that contains only that character. For example, to check if the character 'a' appears in the string "Java", we can use the regular expression .*[a].*. Here, .* means zero or more of any character, and the [a] means exactly one 'a' character.

Download  Run Code

That’s all about checking if a specific character appears in a String in Java.