+84 1649 660 740

Sunday 17 August 2014

Integer Types In Java

The integer types are for numbers without fractional parts. Negative values are allowed. Java provides the four integer types:

TypeStorage RequirementRange(inclusive)
int4 bytes-2,147,483,648 to 2,147,483,637 (just over 2 billion)
short2 bytes-32,768 to 32,767
long8 bytes-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
byte1 byte-128 to 127

In most situations, the int type is the most practical. If you want to represent the number of inhabitants of our planet, you'll need to resort to a long. The byte and short types are mainly intended for specialized applications, such as low-level file handling, or for large arrays when storage space is at a premium.

Under Java, the ranges of the integer types do not depend on the machine on which you will be running the Java code. This alleviates a major pain for the programmer who wants to move software from one platform to another, or even between operating systems on the same platform. In contrast, C and C++ programs use the most efficient integer overflow on a 16-bit system. Since Java programs must run with the same result on all machines, the ranges for the various types are fixed.

Long integer number have a suffix L (for example: 4000L). Hexadecimal number have a prefix 0x (for example: 0xCAFE). Octal number have a prefix 0 (for example: 010 is 8). Naturally, this can be confusing, so we recommend against the use of octal constants.

Starting with Java 7, you can write numbers in binary, with a prefix 0b (for example: 0b1001 is 9). Also starting with Java 7, you can add underscores to number literals, such as 1_000_000 to denote one million. The underscores are for human eyes only. The Java compiler simply removes them.

*Node: In C/C++ the sizes of types such as int and long depend on the target platform. On a 16-bit processor such as the 8086, int are 2 bytes but on a 32-bit process like a Pentium they are 4-byte quantities. Similarly, long values are 4-byte on 32-bit processors and 8-byte on 64-bit processors. These differences make it challenging to write cross-platform programs. In Java, the sizes of all numeric types are platform-independent. Note that Java does not have any unsigned types.

View Project

Download Project

0 comments:

Post a Comment