Gagak
Gagak

Reputation: 161

Java - Problem with casting an int to char

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?

Upvotes: 2

Views: 2582

Answers (3)

Tempestas Ludi
Tempestas Ludi

Reputation: 1165

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));

Upvotes: 1

Nicholas K
Nicholas K

Reputation: 15423

ASCII value of (char) 3 is : End of text

If you want to get the numeric value you need to use numeric value 51 which is the ASCII value of 3:

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

This gives output :

3 51

Complete ASCII table can be found here

Upvotes: 1

Eran
Eran

Reputation: 393791

The char '3' doesn't have a numeric value of 3. Its numeric value is 51.

This will print 3:

int k = 51;
System.out.println((char)k);

The char having a numeric value of 3 is an invisible character.

If you want to convert a single digit int to the corresponding char, you can write

int k = 3;
char three = (char)('0' + k);
System.out.println(three);

Upvotes: 4

Related Questions