• Post Reply Bookmark Topic Watch Topic
  • New Topic

Out put of program  RSS feed

 
Punya Pratap Singh
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
why is out put is coming -126,instead of 127 please clearly Expalin .I guess that there is some sign bit effect but don't understand what is it please help me.

Thanks

class Casting {
public static void main(String [] args) {
long l = 130L;
byte b = (byte)l;
System.out.println("The byte is " + b);
}
}
 
Matt Cartwright
Ranch Hand
Posts: 152
Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you're right, the byte primitive in Java is signed (data types).

internally (at byte code level) the JVM converts 'byte' and 'short' primitives to type 'int'.
The effect we are seeing here is called "(integer) overflow" and leads to a model of so-called "circular arithmetic",
in which the greatest positive integer is followed by the smallest negative integer.

Why not change the representation to hexadecimal?



HTH
Matt
 
Wim Vanni
Ranch Hand
Posts: 96
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Related Ranch Question (RRQ)

Cheers,
Wim
 
Punya Pratap Singh
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Matt Cartwright,but why to print in hexadecimal ?
Thanks Wim.
 
Matt Cartwright
Ranch Hand
Posts: 152
Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
short answer: because it's a byte and not a decimal number, the bits set do count, not its representation in decimal notation
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!