Java Reference
In-Depth Information
However, irrespective of the value in the source
int
variable, the destination
byte
variable will always have a
value between -128 and 127. Like
int
, since
long
is also a bigger data type than
byte
, you need to use explicit cast if
you want to assign the value of a
long
variable to a
byte
variable. For example,
byte b4 = 10;
long num3 = 19L;
b4 = (byte)num3; // OK because of cast
b4 = 19L; // Error. Cannot assign long literal to byte
b4 = (byte)19L; // OK because of cast
It is true that both 19 and 19L represent the same number. However, to the Java compiler, they are different.
19 is an
int
literal, that is, its data type is
int
, whereas 19L is a
long
literal, that is, its data type is
long
.
Java has a class
Byte
(note the upper case
B
in
Byte
), which defines two constants to represent maximum and
minimum values of the
byte
data type,
Byte.MAX_VALUE
and
Byte.MIN_VALUE
.
byte max = Byte.MAX_VALUE;
byte min = Byte.MIN_VALUE;
The short Data Type
The
short
data type is a 16-bit signed Java primitive integer data type. Its range is -32768 to 32767 (or -2
15
to 2
15
- 1).
Generally,
short
variables are used when a program uses a large number of variables whose values fall in the range
of the
short
data type or when dealing with data in a file, which can be easily handled using
short
data type. Unlike
int
and
long
literals, there is no
short
literal. However, you can assign any
int
literal that falls in the range of
short
(-32768 to 32767) to a
short
variable. For example,
short s1 = 12905; // ok
short s2 = -11890; // ok
The value of a
byte
variable can always be assigned to a
short
variable because the range of the
byte
data type
falls within the range of the
short
data type. All other rules for assignment of a value from an
int
or
long
variable to a
short
variable are same as that for the
byte
variable. The following snippet of code illustrates the assignment of
byte
,
int
, and
long
values to
short
variables:
short s1 = 15; // ok
byte b1 = 10; // ok
s1 = b1; // ok
int num1 = 10; // ok
s1 = num1; // A compile-time error
s1 = (short)num1; // ok because of cast from int to short
s1 = 35000; // A compile-time error of an int literal outside the short range
long num2 = 555L; // ok
s1 = num2; // A compile-time error
s1 = (short)num2; // ok because of the cast from long to short
s1 = 555L; // A compile-time error
s = (short)555L; // ok because of the cast from long to short