Wednesday, July 24, 2013

Integer Data Types

There are four types of variables that you can use to store integer data. All of these are signed; that is,they can store both negative and positive values. The four integer types differ in the range of values they can store, so the choice of type for a variable depends on the range of data values you are likely to need. The four integer types in Java are:

byte : -128 to +127 and occupy 1 byte (8 bits)
short : -32768 to 32767 and occupy 2 bytes (16 bits)
int : -2147483648 to 2147483647 and occupy 4 bytes (32 bits)
long : -9223372036854775808 to 9223372036854775807 and occupy 8 bytes (64 bits)

Although I said the choice of type depends on the range of values that you want to be able to store, in practice you’ll be using variables of type int or type long to store integers most of the time, for reasons that I’ll explain a little later. Let’s take a look at declarations of variables of each of these types:

byte smallerValue;
short pageCount;
int wordCount;
long bigValue;

Each of these statements declares a variable of the type specified.

The range of values that can be stored by each integer type in Java, as shown in the preceding table, is always the same, regardless of what kind of computer you are using. This is also true of the other primitive types that you will see later in this chapter and has the rather useful effect that your program will execute in the same way on computers that may be quite different. This is not necessarily the case with other programming languages.

Of course, although I have expressed the range of possible values for each type as decimal values, integers are stored internally as binary numbers, and it is the number of bits available to store each type that determines the maximum and minimum values.

For each of the binary numbers shown here, the leftmost bit is the sign bit, marked with an s. When the sign bit is 0 the number is positive, and when it is 1 the number is negative. Binary negative numbers are represented in what is called 2’s complement form. If you are not familiar with this, you will find an explanation of how it works in Appendix B.

No comments:

Post a Comment

Thanks for Commenting......