Character Class Methods in Java
A password rule says "at least one capital letter, one digit and one symbol". To check it, you look at the password one character at a time and ask: is this a letter? A digit? Upper case? The Character class (the wrapper for char) answers exactly these questions, and it understands letters and digits from every language, not just English.
Checking a Password
public class Password {
public static void main(String[] args) {
String pwd = "Navika@2026";
int upper = 0, lower = 0, digits = 0, other = 0;
for (char c : pwd.toCharArray()) {
if (Character.isUpperCase(c)) {
upper++;
} else if (Character.isLowerCase(c)) {
lower++;
} else if (Character.isDigit(c)) {
digits++;
} else {
other++;
}
}
System.out.println("Upper " + upper + ", lower " + lower
+ ", digits " + digits + ", symbols " + other);
boolean strong = upper > 0 && digits > 0 && other > 0
&& pwd.length() >= 8;
System.out.println("Strong: " + strong);
}
}Upper 1, lower 5, digits 4, symbols 1
Strong: trueHow it works
toCharArray()gives the characters one by one.Character.isUpperCase,isLowerCaseandisDigitclassify each one. Anything left over (here@) counts as a symbol.- The password passes all four rules, so it's strong.
Quick Reference
| Method | 'N' | 'a' | '7' | ' ' | '_' |
|---|---|---|---|---|---|
isLetter(c) | true | true | false | false | false |
isDigit(c) | false | false | true | false | false |
isLetterOrDigit(c) | true | true | true | false | false |
isUpperCase(c) | true | false | false | false | false |
isWhitespace(c) | false | false | false | true | false |
toUpperCase(c) | N | A | 7 | ' ' | _ |
These methods work for every language: Character.isLetter('अ') (a Hindi letter) is true, and Character.isDigit('٣') (the Arabic digit three) is true as well.
A char Is Secretly a Number
Every char is stored as a number, its Unicode code: 'A' is 65, 'a' is 97 and '7' is 55. That's why character arithmetic works:
| Expression | Result | Why |
|---|---|---|
(int) 'A' | 65 | The code of A |
(char) ('a' + 1) | b | One code after a |
'7' - '0' | 7 | 55 minus 48: the digit's value |
Character.getNumericValue('7') | 7 | The same, written clearly |
Common Mistakes
Comparing with c >= 'A' && c <= 'Z' for "is a letter". It misses lowercase and every non-English letter; use Character.isLetter.
Treating '7' as the number 7. It's code 55; convert with c - '0' or getNumericValue.
Forgetting that toUpperCase returns a value. Character.toUpperCase(c); alone doesn't change c.
Practice
- Easy: Count the vowels, consonants, digits and spaces in
"Advitha joined in 2026". - Harder: Write
static boolean isValidUsername(String u)that allows only letters, digits and underscores, must start with a letter, and must be 4 to 12 characters long.
Key Takeaways
Was this tutorial helpful?