The Flavors of Integer

The next set of primitive types in Java contains what are known as the integer types:

  • byte

  • int

  • long

  • short

The types of integer differ only in the range of values they can hold. For instance, a byte cannot hold any number that is greater than 127, but a long can easily hold the world's population count (many times over actually).

Why are there so many types of integer? Couldn't you just declare every integer variable you need as a long and not worry about size restrictions? Although this would work in many cases, it is a confusing and inefficient use of a limited resource, namely the memory available to execute your programs. When you specify a meaningful integer type for a variable, you are providing information about the ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.