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')
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.
Related Questions
A student is trying to convert the string present in x to a numerical value, so that he can find the square root of the converted value. However the code has an error. Name the error (syntax / logical / runtime). Correct the code so that it compiles and runs correctly.
String x= "25"; int y=Double.parseDouble(x); double r=Math.sqrt(y); System.out.println(r);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);Assertion (A): Integer class can be used in the program without calling a package.
Reason (R): It belongs to the default package java.lang.
- Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of Assertion (A)
- Both Assertion (A) and Reason (R) are true and Reason (R) is not a correct explanation of Assertion(A)
- Assertion (A) is true and Reason (R) is false
- Assertion (A) is false and Reason (R) is true
The method to convert a lowercase character to uppercase is:
- String.toUpperCase( )
- Character.isUppercase( char )
- Character.toUpperCase( char )
- toUpperCase ( )