0

the below code is not printing anything, can someone tell me what is exactly wrong with this

public class Main
{
    public static void main(String[] args) {
        int i = 2;
        char c = (char)i;
        System.out.println(c);
    }
}
  • It's printing the character with the ASCII code 2, which is known as STX. A `char` is an unsigned 16 bit value. – tgdavies Sep 19 '21 at 06:51
  • As to what is wrong with it: please tell us what you want it to do. – tgdavies Sep 19 '21 at 06:52
  • `(char)i;` will treat value of `i` as position of character in Unicode Table. If you want to get character `'2'` and you know that `i` contains a digit you can use something like `(char)('0'+i)` to calculate index of character "i positions higher" than `'0'` character (since they are grouped as `'0', '1', '2', '3', .., '9') and then cast that index to character. – Pshemo Sep 19 '21 at 06:54
  • @tgdavies Java's internal character code is Unicode. Not ASCII. –  Sep 19 '21 at 07:51
  • True, but the first 127 Unicode characters are ASCII characters too. – tgdavies Sep 19 '21 at 07:57

0 Answers0