The integer types – byte, short, int, long
An integer type is used to store an integer (whole number) value. An integer value is one of 0, ~+mn~1, ~+mn~2, ~+mn~3, ~+mn~4, etc. However, on a computer, the largest and smallest integers (and all those in between) which can be stored are determined by the number of bits used to store an integer. The more bits we use, the greater the range.
The following shows the length and the range of integers which can be stored in each type.
byte (8 bits = 1 byte) : -128 to + 127
short (16 bits = 2 bytes) : -32,768 to +32,767
int (32 bits = 4 bytes) :
-2,147,483,648 to +2,147,483,647
long (64 bits = 8 bytes) :
-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
In general, if n bits are used to store an integer, the range of numbers which can be stored is -2(n-1) to +2(n-1) - 1. Integer constants can be written in various ways. The most common form is the one we are all accustomed to, using decimal digits, for example, 354, -1, 32905 and 987654321. Note that you are allowed to use only a possible sign (plus or minus) followed by digits 0 to 9. In particular, you cannot use commas as you might do to separate thousands; thus 1,713 is an invalid integer constant—you must write it as 1713.
Octal constants are numbers written in base 8, using digits 0 to 7. In Java, if a number begins with 0 (zero), it is considered an octal constant. For example, 047 is an octal number whose decimal equivalent is 39.
Hexadecimal constants are numbers written in base 16, using digits 0 to 9 and letters A to F (or a to f) to represent the hexadecimal ‘digits’ 10 to 15. In Java, a hexadecimal number begins with 0x or 0X (zero ex). For example, 0x27 (or 0X27) is a hexadecimal number whose decimal equivalent is 39.
In this series, we will generally use decimal integers.
When you write an integer constant in a program, it is considered to be of type int. In the statement
a = 14;
14 is considered an int.
If you want an integer constant to be long, you must end it with L or l (ell, not one —always use L to avoid confusion). Thus 39L is a long constant. You may do this if you feel that your calculation might produce a result which is too large to fit in an int and you want to force it to be done using long precision.
For example, if j is an int, the expression j * 39 (meaning j multiplied by 39; * denotes multiplication) is also an int but j * 39L is of type long.
For most of this series, we will use int for working with integers.
In the article Java Integer Arithmetic, we will show how to form integer expressions and how they are evaluated.