Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of char in java

Tags:

java

I'm seeing both char and short are two bytes each, also the following is valid:

char a = 'x';
int b =  a;
long c = a;

However when I do short d = a; I'm getting an error that cannot convert from char to short. even though both are two bytes.

One use of char I can see is when you print it, it displays the character. Is that the only use of char?

like image 499
Rnet Avatar asked Feb 22 '26 06:02

Rnet


1 Answers

In Java the data type char is an unsigned 2 byte variable while a short is signed 2 byte variable. Because of this difference you cannot convert a char to a short because a char has that extra bit that isn't the signed bit.

This means that if you convert char to a short you would have to truncate the char which would cause the complaining.

like image 78
Wei-Lee Avatar answered Feb 23 '26 21:02

Wei-Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!