1 //1. Using Regex
2
3import java.util.regex.Matcher;
4import java.util.regex.Pattern;
5
6public class JavaHungry {
7 public static void main(String args[]) {
8 String inputString = "Alive*is*Awesome$";
9 Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
10 Matcher matcher = pattern.matcher(inputString);
11 boolean isStringContainsSpecialCharacter = matcher.find();
12 if(isStringContainsSpecialCharacter)
13 System.out.println(inputString+ " contains special character");
14 else
15 System.out.println(inputString+ " does NOT contain special character");
16 }
17}
18
19//Output:
20//Alive*is*Awesome$ contains special character
21
22
23//2. Without Using Regex
24
25public class JavaHungry {
26 public static void main(String args[]) {
27 String inputString = "Alive*is*Awesome$";
28 String specialCharactersString = "!@#$%&*()'+,-./:;<=>?[]^_`{|}";
29 for (int i=0; i < inputString.length() ; i++)
30 {
31 char ch = inputString.charAt(i);
32 if(specialCharactersString.contains(Character.toString(ch))) {
33 System.out.println(inputString+ " contains special character");
34 break;
35 }
36 else if(i == inputString.length()-1)
37 System.out.println(inputString+ " does NOT contain special character");
38 }
39 }
40}