-2

Would any one be able to explain what this code does?

if ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')){}

where x is an int. However I am not entirely sure how it works, would any one be able to provide me with an explanation? If anyone needs more details please comment below rather than down voting my question.

Maja
  • 59
  • 1
  • 11

2 Answers2

2

This code compare x to the ASCII code of A, Z... You can check there values in the ASCII table.


A verbal expression of your if-statement could be:

"If x value is the ASCII code of a letter (uppercase or not)."

Mistalis
  • 17,793
  • 13
  • 73
  • 97
  • Because the ASCII code of letters coincides with the UNICODE code. – Maurice Perry Mar 10 '17 at 09:20
  • Thank you for your help! – Maja Mar 10 '17 at 09:29
  • Your verbalization only applies to the [Basic Latin](http://www.unicode.org/charts/nameslist/index.html) letters. There are thousands of other letters that one Java `char` (UTF-16 code unit) can represent and many thousands more that two Java `char`s—a Java `String`—can represent. (One or two UTF-16 code units encode each single Unicode codepoint). It's quite a long tale to explain how a `char` can be an ASCII value, starting from the [Java definition](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html) of `char` as a UTF-16 code unit. And, one wonders what the point would be. – Tom Blodget Mar 11 '17 at 00:33
2

You can initialize an int with a char type because, the code of char can be represented with an int so for example :

char x = 'A';
int i = x;
System.out.println((int)x);//this will print 65
System.out.println(i);//this will print 65

The code of char A is 65 so for that you can compare a char with int in your case : if ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')){} you can also take a look here Java - char, int conversions

Community
  • 1
  • 1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140