Computer Applications
Chhavi wants to check whether a character variable ch contains an uppercase letter (A-Z).
She writes the following statement, which is incorrect:
if (ch == "A" && ch == "Z")
What will be the correct statement?
A. if (Character.isUpperCase(ch))
B. if (ch >= 65 && ch <= 90)
C. if (ch >= 'A' && ch <= 'Z')
Java Library Classes
3 Likes
Answer
A, B and C
Reason — To check if a character variable ch contains an uppercase letter (A-Z), we have three valid approaches, all of which are correct:
A. if (Character.isUpperCase(ch)) — Character.isUpperCase(ch) method from the Character class directly checks if ch is an uppercase letter.
B. if (ch >= 65 && ch <= 90) — Uppercase letters 'A' to 'Z' have ASCII values 65 to 90. As characters are internally stored as their unicode values, hence, this is also a valid way to determine if ch is an uppercase letter.
C. if (ch >= 'A' && ch <= 'Z') — Since Java treats characters as numbers internally, comparing ch with 'A' and 'Z' works just like using ASCII values. So this way is also correct.
Answered By
1 Like
Related Questions
Predict the output of the following code snippet:
char ch='B', char chr=Character.toLowerCase(ch); int n=(int)chr-10; System.out.println((char)n+"\t"+chr);Primitive data types are built in data types which are a part of the wrapper classes. These wrapper classes are encapsulated in the java.lang package. Non primitive datatypes like Scanner class are a part of the utility package for which an object needs to be created.
(a) To which package the Character and Boolean classes belong?
(b) Write the statement to access the Scanner class in the program.