Java ProgramsControl FlowCheck Character Is Special Character

Check Character Is Special Character in Java

beginner·  Control Flow  ·  Conditional Statements

Problem

A special character is anything that's neither a letter nor a digit — punctuation, symbols, and similar characters fall outside both the alphabet and digit ranges.

Given a single character, determine whether it is a special character.

Input
'@'
Output
'@' is a special character: true

Java Program

Java
public class SpecialCharacterCheck { public static void main(String[] args) { char ch = '@'; boolean isAlphabet = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); boolean isDigit = (ch >= '0' && ch <= '9'); boolean isSpecial = !isAlphabet && !isDigit; // neither letter nor digit — includes whitespace too System.out.println("'" + ch + "' is a special character: " + isSpecial); } }

Output

'@' is a special character: true

Core Logic

Reusing the same alphabet and digit range checks, but requiring that neither one matches, identifies everything left over as a special character.

How It Works
  1. 1isAlphabet checks the same 'a'-'z' / 'A'-'Z' ranges used to test for letters.
  2. 2isDigit checks the same '0'-'9' range used to test for digits.
  3. 3!isAlphabet && !isDigit is true only when the character matched neither range.
For ch = '@', neither the letter ranges nor the digit range match, so both negations are true and it's reported as a special character.
💡

Key Point: This treats spaces the same as punctuation — anything outside the letter and digit ranges counts as 'special', including whitespace.

Key Concepts

character range checklogical NOTcombined conditions

Approach 2: Using Character.isLetterOrDigit()

Java
public class SpecialCharacterCheckBuiltIn { public static void main(String[] args) { char ch = '@'; boolean isSpecial = !Character.isLetterOrDigit(ch); System.out.println("'" + ch + "' is a special character: " + isSpecial); } }

Output

'@' is a special character: true

Core Logic

Java's Character class combines the letter and digit checks into one method, so a single negation covers both at once.

How It Works
  1. 1Character.isLetterOrDigit(ch) returns true if the character is either a letter or a digit.
  2. 2Negating that result with ! gives exactly the 'special character' condition, without checking letters and digits as two separate steps.
Character.isLetterOrDigit('@') returns false, so negating it reports true.
💡

Key Point: This is functionally identical to the manual version but reads more directly as 'not a letter or digit', with the added benefit of covering Unicode letters and digits too.

Key Concepts

Character.isLetterOrDigit()logical NOT

Related Programs