Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can't understand such an output..

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Options :
1)It generates a compile error at line 4
2)It generates a compile error at line 5
3)If the cast on line 5 were miited, then line 5 would not compile
4)The code compiles and prints "b=0"
5)The code compiles and prints"b= -2"
6)The code compiles and prints "b= -3"
7)The code compiles and prints "TROUBLE"
Ans :3) and 6)
I cannot understand from where did this "-3" come?
Please explain?
Sonir
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All numbers in java are signed, ie, they can be + or -.
The lines
short s = 0x00FD;
byte b = (byte)s;
cause the value 0xFD to be stored in the variable b.
0xFD is hexidecimal for -3 using signed numbers.
just remember that OxFF is -1, and count backwards from there...
FF = -1
FE = -2
FD = -3
FC = -4...
...
80 = -128
...
7F = 127
7E = 126...
etc.
Rob
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic