Classes and Primitive Types


Primitive types

The types int, long, double, boolean and char are called primitive types. You can recognize them because they start with a lower case letter.

Values whose types are primitive types are not objects, and they are handled differently from objects. For example, if variables x and y have type int, then expression x == y is true if x and y are the same integer. There is no concept of a reference to a primitive value. There are just the values themselves.


Classes

Types whose names start with upper case letters are called classes. A class is a type of objects. For example, String is a class, so a string is an object.


Boxing

Sometimes you would like to treat a primitive value as if it is an object. For example, many objects can respond to request toString( ), which converts the object to a string, and you might want to convert an integer n to a string using n.toString( ). (The toString( ) request is similar to the Cinnameg $ function.)

Java handles that by having a class for each primitive type. The class that corresponds to type int is called Integer. If you use an integer as if it is an object, the integer is converted to class Integer for you. Most of the time you can ignore that, but there are times when it is an important consideration.

Conversion of a primitive value to an object is called boxing, and conversion back from the object to the corresponding primitive value is called unboxing. Both conversions are inserted automatically by the compiler where they are needed. For example, you can write

  Integer I = 0;
The primitive value 0 is converted to an object of type Integer. You can do explicit unboxing. If I has type Integer then I.intValue( ) is the value (of type int) that object I holds.

Remember that, when the equality operator == is used to compare two object references, it asks whether they refer to the same object. Suppose that you write the following.

  Integer A = 1;
  Integer B = 1;
  boolean x = (A == B);
What would you expect the value of x to be? Since A and B are created as separate objects (each holding information 1) they are not the same object, and x is false. On the other hand, expression A.intValue( ) == B.intValue( ) has value true, since it asks whether objects A and B are holding the same information.

The following table shows the classes that correspond to some primitive types.

Primitive type Corresponding class
int Integer
long Long
double Double
boolean Boolean
char Character