Java - Problem with casting an int to char

Gagak :

I have a bit of confusion regarding casting from int to char data type, this is what i have;

int k = 3;
System.out.println((char)k + " " + k)

The output should have been

3 3

yet, i got this instead

 3

Could somebody explains to me why is this happening?

Tempestas Ludi :

In addition to the other answers: If you know for sure that 0 <= k <= 9, you can use

System.out.println((char)(k + '0'));

to print the 'charified' version of your integer. If k < 0 or k > 9, there isn't a single char (character) describing it. In that case, you'll have to use a string, which is basically an array of chars:

System.out.println(Integer.toString(k));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117262&siteId=1