Java Reference
In-Depth Information
Java has a class Long (note the upper case L in Long ), which defines two constants to represent maximum and
minimum values of long data type, L ong.MAX_VALUE and Long.MIN_VALUE .
long max = Long.MAX_VALUE;
long min = Long.MIN_VALUE;
The byte Data Type
The byte data type is an 8-bit signed Java primitive integer data type. Its range is -128 to 127 (-2 7 to 2 7 - 1). This is the
smallest integer data type available in Java. Generally, byte variables are used when a program uses a large number
of variables whose values fall in the range -128 to 127 or when dealing with binary data in a file or over the network.
Unlike int and long literals, there are no byte literals. However, you can assign any int literal that falls in the range of
byte to a byte variable. For example,
byte b1 = 125;
byte b2 = -11;
If you assign an int literal to a byte variable and the value is outside the range of the byte data type, Java
generates a compiler error. The following piece of code will produce a compiler error:
// An error. 150 is an int literal outside -128 to 127
byte b3 = 150;
Note that you can only assign an int literal between -128 and 127 to a byte variable. However, this does not imply
that you can also assign the value stored in an int variable, which is in the range of -128 to 127, to a byte variable. The
following piece of code will generate a compiler error, because it assigns the value of an int variable, num1 , to a byte
variable, b1 :
int num1 = 15;
// OK. Assignment of int literal (-128 to 127) to byte.
byte b1 = 15;
// A compile-time error. Even though num1 has a value of 15, which is in the range -128 and 127.
b1 = num1;
Java does not allow you to assign the value of a variable of a higher range data type to the variable of a lower range
data type because there is a possible loss of precision in making such an assignment. To make such an assignment
from int to byte , you must use a cast, as you did in the case of the long -to- int assignment. The assignment of num1 to
b1 can be rewritten as follows:
b1 = (byte)num1; // Ok
After this cast from int to byte , the Java compiler would not complain about the int -to- byte assignment. If
num1 holds a value that cannot be correctly represented in the 8-bit byte variable b1 , the higher order bits (9 th to
32 nd ) of num1 are ignored and the value represented in the lower 8 bits is assigned b1 . In such a case of int -to- byte
assignment, the value assigned to the destination byte variable may not be the same as the value of the source int
variable if the value of the source variable falls outside the range of byte data type.
 
Search WWH ::




Custom Search