When i execute this code it gives value of s as -7616. Why so? Is this because loss of data while converting it to short from int or something else?
public static void main(String[] args) {
// TODO code application logic here
short s=0;
int x=123456;
int i=8;
s +=x;
System.out.println(s);
}
Good question! It made me think about things I haven't thought about in a long while and I had to brush up on a couple of concepts. Thanks for helping me knock the rust off my brain.
For me this type of question is best visualized in binary (for reasons that will quickly become apparent):
Your original number (forgive the leading zeroes; I like groups of 4):
0001 1110 0010 0100 0000
A short, however, is a 16-bit signed two's complement integer according to the Java Language Specification (JLS) section 4.2. Assigning the integer value 123456 to a short is known as a "narrowing primitive conversion" which is covered in JLS 5.1.3. Specifically, a "narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T."
Discarding all but the lowest 16 bits leaves us with:
1110 0010 0100 0000
In an unsigned integer this value is 57,290, however the short integer is a signed two's complement integer. The 1 in the leftmost digit indicates a negative number; to get the value of the number you must invert the bits and add 1:
Original:
1110 0010 0100 0000
Invert the bits:
0001 1101 1011 1111
Add 1:
0001 1101 1100 0000
Convert that to decimal and add the negative sign to get -7,616.
Thanks again for asking the question. It's okay to not know something so keep asking and learning. I had fun answering...I like diving into the JLS, crazy, I know!