Java Reference
In-Depth Information
An
int
literal can also be represented using the binary number format. All
int
literals in the binary number format
start with 0b or 0B, that is, zero immediately followed by an uppercase or lowercase B. The following are examples of
using
int
literals in the binary number format:
int num1 = 0b10101;
int num2 = 0b00011;
int num3 = 0b10;
int num4 = 0b00000010;
The following assignments assign the same decimal number 51966 to an
int
variable
num1
in all four different
formats:
num1 = 51966; // Decimal format
num1 = 0145376; // Octal format, starts with a zero
num1 = 0xCAFE; // Hexadecimal format, starts with 0x
num1 = 0b1100101011111110; // Binary format starts with 0b
Java has a class named
Integer
(note the upper case
I
in
Integer
), which defines two constants to represent
maximum and minimum values for the
int
data type,
Integer.MAX_VALUE
and
Integer.MIN_VALUE
. For example,
int max = Integer.MAX_VALUE; // Assigns maximum int value to max
int min = Integer.MIN_VALUE; // Assigns minimum int value to min
The long Data Type
The
long
data type is a 64-bit signed Java primitive data type. It is used when the result of calculations on whole
numbers may exceed the range of the
int
data type. Its range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
(-2
63
to 2
63
- 1). All whole numbers in the range of
long
are called integer literals of
long
type.
51 is an integer literal. What is its data type:
int
or
long
? An integer literal of type
long
always ends with L
(or lowercase l). This topic uses L to mark the end of an integer literal of the
long
type, because l (lowercase L) is often
confused with 1 (digit one) in print. The following are examples of using a integer literal of
long
type:
long num1 = 0L;
long num2 = 401L;
long mum3 = -3556L;
long num4 = 89898L;
long num5 = -105L;
■
Tip
25L is an integer literal of
long
type whereas 25 is an integer literal of
int
type.
Integer literals of
long
type can also be expressed in octal, hexadecimal, and binary formats. For example,
long num1;
num1 = 25L; // Decimal format
num1 = 031L; // Octal format
num1 = 0X19L; // Hexadecimal format
num1 = 0b11001L; // Binary format