Print a char with println

1

I have this code:

System.out.println((char)-1);

I get it, with -2 with also, with -3 it changes to and with -4 it does not print anything.

Why these results?

Thanks in advance.

Greetings

    
asked by pelaitas 27.04.2018 в 13:04
source

2 answers

3

When you do

char a=(char)-1 ;

An underflow occurs: since char goes from 0 to 65535, if you exceed these values, an module operation is done and the rest is added. Therefore it is the same as doing

char a=(char)65535;

Therefore,

(char)-4

is the same as

(char)65532

If it is not shown it is because it may not be a printable character or the typography used does not include that value or it is printable but not by itself, but accompanying some other character.

    
answered by 27.04.2018 в 15:35
1

The ASCII table goes from 0 to 255, so if you convert any number within this range to char you will not have problems.

If you leave this range (as is your case) you will not find any character for what will come out .

You are assigning char negative numbers, but since char is a numeric representation of a character, this is not possible, since it is outside the representation range.

If you want to print a negative number per screen it is not necessary to convert it to char and you can print directly -2 .

    
answered by 27.04.2018 в 13:14