Every program you write deals with data in some form. Java has several types of data it can work with, and this chapter covers some of the most important. Although Java is a language based on classes and all Java programs are built from classes, not all data types in Java are classes. In Java, there are two categories into which data types have been divided using this distinction:
PrimitivesPrimitives are data types whose state represents a number, a character, or a true/false indication. Primitive types are not class types; they do not provide any behavior associated with the type-appropriate values they hold. Java has eight primitive types that should look familiar to you from other languages:
As you proceed through this chapter, each of these types is covered in detail. For now, take a look at Table 3.1, which shows the numerical limits associated with each type. Table 3.1. Primitive Data Types in the Java Language
You might have heard Java described as a platform-independent language. The values shown in Table 3.1 are language features that support that statement. Unlike some languages, a given primitive type in Java is always represented using the same number of bits and the same supported range regardless of the platform. You will never be concerned about a 2-byte int versus a 4-byte int in Java because a Java int is always 4 bytes. Porting your program from one platform to another will not change how your primitive type variables are allocated and used. Note Although you should always declare a variable using a type that is sufficiently large to hold its possible values, the storage size associated with the primitive types should otherwise be transparent to you. Unlike C/C++, Java does not use pointers and pointer arithmetic to locate contiguously stored variables based on their size. Notice that Java has no equivalent to the C/C++ sizeof operator to support such usage. Reference TypesClasses, interfaces, and arrays are known as reference types in Java. When you declare a variable of a reference type, you are specifying that the variable will refer, or point, to an object instead of holding a single value as in the case of a primitive. This makes sense for classes because class instances are objects that have associated behavior and state that can be represented with many values as opposed to one. However, it might seem strange to you to see arrays in the same category. You'll get a closer look at the details a little later in this chapter, but arrays in Java are true objects whose elements can be either primitives or references to other objects. |