How to Check String Contains Special Characters in Java

In this tutorial, we will be learning how to check if the string contains special characters or not in java. There are two ways to achieve our goal:

1. Using regex, we will be using java.util.regex.Matcher and java.util.regex.Pattern class.

2. Simply using String class methods i.e without using regex

Before moving on to the solution, first, understand the question by looking at some examples.

Read Also: String Interview Questions

Input: Alive*is*Awesome$
Output: true 
Explanation: Input string contains * and $ as special characters

Input: Be)in^present
Output: true
Explanation: Input string contains ) and ^ as special characters

Input: JavaHungry123
Output: false
Explanation: Input string does not contain special characters

What is Special Character?

According to YourDictionary, non-alphabetic and non-numeric characters such as #, @ are called special characters.

Java Program to Check String Contains Special Characters

 1. Using Regex


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

public class JavaHungry {
    public static void main(String args[]) {
        String inputString = "Alive*is*Awesome$";
        Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
        Matcher matcher = pattern.matcher(inputString);
        boolean isStringContainsSpecialCharacter = matcher.find();
        if(isStringContainsSpecialCharacter)
            System.out.println(inputString+ " contains special character");
        else    
            System.out.println(inputString+ " does NOT contain special character");
    }
}

Output:
Alive*is*Awesome$ contains special character


2. Without Using Regex 


public class JavaHungry {
    public static void main(String args[]) {
        String inputString = "Alive*is*Awesome$";
        String specialCharactersString = "!@#$%&*()'+,-./:;<=>?[]^_`{|}";
        for (int i=0; i < inputString.length() ; i++)
        {
            char ch = inputString.charAt(i);
            if(specialCharactersString.contains(Character.toString(ch))) {
                System.out.println(inputString+ " contains special character");
                break;
            }    
            else if(i == inputString.length()-1)     
                System.out.println(inputString+ " does NOT contain special character");
        }
    }
}

Output:
Alive*is*Awesome$ contains special character

That's all for today, please mention in comments in case you know any other way to check string contains special characters in java.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry