Check if a String contains a special character

To check if a String contains a special character in Java, you can use a regular expression to match any character that is not a letter or a digit. Here is an example of how to do this:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpecialCharacterExample {

    public static void main(String[] args) {
        String input = "Hello World!";
        Pattern p = Pattern.compile("[^a-zA-Z0-9]");
        Matcher m = p.matcher(input);
        boolean containsSpecialCharacter = m.find();
        System.out.println(containsSpecialCharacter);
    }

}

This example uses the Pattern and Matcher classes from the java.util.regex package to check if the input string contains any characters that are not letters or digits. The regular expression [^a-zA-Z0-9] matches any character that is not a letter or a digit. The find() method returns true if the input string contains any characters that match the regular expression.

Alternatively, you can use the matches() method to check if the entire input string matches the regular expression:

boolean isSpecialCharacter = input.matches("[^a-zA-Z0-9]");

I hope this helps. Let me know if you have any questions.