+ 1
how this logics works? This is a program of capitalize a letter without using pre method
public class{ public static void main(String[]args) { String s = "java is best"; char[] ch = s.toCharArray(); for(int i =0; i<s.length(); i++) { if(ch[i]>= 'a' && ch[i]<='z') { ch[i] = (char) ((int) ch[i] -32); } } System.out.print(ch); } } Output: JAVA IS BEST
3 Answers
+ 8
Sid Harth Sharma if you study the ASCII character set and their integer values, you may notice that the difference between uppercase letters and lowercase letters is exactly 32. 'A' is 65, 'a' is 97. So, any lowercase letter is converted to uppercase by subtracting 32 from its ASCII value.
An alternative to subtraction (and slightly faster technique) in this case is to recognize that 32 is a single bit (bit5), and use a bitwise operator either to clear it or toggle it:
ch[i] &= ~32; //clear bit5: 'a' --> 'A'
ch[i] ^= 32; //toggle bit5: 'a' <--> 'A'
ch[i] |= 32; //set bit5: 'A' --> 'a'
+ 3
using the *tricky solution with +/- 32 arithmetic* can be found frequently in codings. but there is also a dark side of this procedure.
- if you take a look to the unicode table, you can see that the difference between a *lower* and its *upper* representation is not always 32, especially
when we are talking about non latin unicode groups.
- not every character has 2 representations, so using the mentioned procedure can show an unexpected result
to get rid of this issue, it is recommended to use the functions / methods that all programming languages are providing to do the *upper to lower* conversion or vice versa.
+ 1
but 2x cast is redundant
//char a = (char) ((int) 'a' -32)
char a = 'a' -32;
System.out.println( a ); // A