Java – 2- Checking character properties

Normally we tend to check the character by comparing with ‘a’ or ‘z’ or ‘X’ or ‘1’ or ‘:’ but this is considered wrong and we should avoid comparing characters like this

Why is this not efficient?

Consider the following code

if(ch == 'a' || ch  >= '0'){
//some code

The above code will work only for English and few other languages. For the sake of working with internationalization we should modify the code to

if(Character.isDigit(ch) || Character.isUpperCase(ch))

Some of the properties of Characters which is useful are

  • isDigit
  • isLetter
  • isLetterOrDigit
  • isLowerCase
  • isUpperCase
  • isSpaceChar
  • isDefined

Complete list of properties of Characters are here

Note: We can also compare the character with their corresponding ASCII values


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: