Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Jan 28, 2000

Be Aware Of The Signed Byte

Java lets you cast an integer into a byte and vice versa. While this provides power and flexibility, we should be aware that Java's byte data type is signed, meaning that the leftmost bit (the 8th bit) of a byte is reserved for the sign of the data it holds (1 to indicate negative, and 0 to indicate positive). This may cause unexpected results especially if we try to compare a byte with an integer. Looking at the following code snippet:
 
    byte aByte; 
    int anInt = 128; 
    aByte = (byte)anInt; 
    if (aByte == anInt) 
    { 
       System.out.println(""+anInt+" equals "+aByte); 
    } 
    else 
    { 
       System.out.println(""+anInt+" is not "+aByte); 
    } 
The output of this code will be:
 
    
    -128 is not 128 
Which may be unexpected since we cast the integer value of 128 into a byte, only to get -128.

This happened because the binary representation of 128 is 10000000, with the 8th bit being 1. Java's byte data type takes only 8 bits. And, in Java, byte is a signed data type with its 8th bit reserved for the sign of the value it contains. So, instead of intended value of 128, we ended up with -128. This kind of mistakes can be the source of extremely hard to find bugs.

To avoid this type of bugs, we should pay attention to the range of values that data types can contain. The following may be used as a guideline:

— the integral types: * byte, whose values are 8-bit signed two's-complement integers * short, whose values are 16-bit signed two's-complement integers * int, whose values are 32-bit signed two's-complement integers * long, whose values are 64-bit signed two's-complement integers

— the floating point types * float, whose values are 32-bit IEEE 754 floating-point numbers * double, whose values are 64-bit IEEE 754 floating-point numbers

— the character type char, whose values are 16-bit Unicode characters

— the boolean type, whose values are true and false

Behrouz Fallahi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date