Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

java - Why is casting to short to char is a narrowing conversion?

A narrowing conversion is when putting a data type that can hold a bigger value into a data type that can hold at max a lesser value.

long l = 4L;
int i = (int)l;

However I don't understand why a short into a char is a narrowing conversion but I've the intuition it is related to signed/unsigned of those two datatypes but I can't explain why.

short s = 4; // short max value is 32767
char c = (char)s; // char max value is 65535 

It looks like it would be a widening conversion or at the very least neither narrowing neither widening since they are both 16 bits and can hold the same number of values.

    System.out.println((int)Character.MIN_VALUE); //0
    System.out.println((int)Character.MAX_VALUE); //65535 
    System.out.println(Short.MIN_VALUE); //-32768
    System.out.println(Short.MAX_VALUE); //32767
    //65535 = 32768+32767
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because a short is capable of holding negative values while char isn't as you might have seen from Character.MIN_VALUE. Let me give a few examples.

  short s = -124;
  char c = 124; // OK, no compile time error
  char d = -124; // NOT OK, compile time error since char cannot hold -ve values
  char e = s; // NOT OK, compile time error since a short might have -ve values which char won't be able to hold
  char f = (char)s; // OK, type casting. The negative number -124 gets converted to 65412 so that char can hold it
  System.out.println((short)f); // -124, gets converted back to a number short can hold because short won't be able to hold 65412
  System.out.println((int)f); // 65412, gets converted to 65412 because int can easily hold it.  

A (negative) number -n when cast to char, becomes 2^16-n. So, -124 becomes
2^16-124 = 65412

I hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...