Reference Data Types
Home ] Up ] Program Structure & Environment ] Comments ] Primitive Data Types ] [ Reference Data Types ] No Preprocessor ] Typesafe enums ]

 

 

The Primitive Data Types are:

boolean, char, byte, short, int, long, float, double

Everything else is a Reference Type

  • Objects
  • Arrays

For example:

Grommet g,h;
g = new Grommet();// g refers to a Grommet object
h = g;            // h refers to the same Grommet object

Major Differences Between Primitive and Reference Types

Primitive Types Reference Types

Can be declared locally within a function.

References can be declared locally, but the objects themselves are always newed from the heap.

Assigning one to another copies the value.

Assigning one to another adds a new reference to an object.
To copy one object to another, you use the clone() method.

Function arguments passed by value.

Function arguments passed by reference. (Arguments are 'references, passed by value'.)

== and != operators compare values.

== and != operators test whether references refer to the same object.
To compare values, you typically use the equals() method.

Each type has a default initial value.

Initial value of a reference is null, meaning absence of reference. You can explicitly set a reference to null by assigning it.

Other Points

Java has no pointers!!!
  • This is goodness -- believe me!
  • It isn't as restrictive as you might first think, if you're a C or C++ programmer.
You always use the new operator to create an instance of a class (object)
  • There is no delete operator!
  • Java takes care of cleaning up using a technique called garbage collection.

Here's How References Work:

  • Each assignment adds a new reference to the object.
  • Each assignment from null removes the reference to the object.
  • When the reference count goes to zero, the object is a candidate for garbage collection.

Summary of Reference Types (Java in a Nutshell, Flanagan)

  • All objects and arrays are handled by reference.
  • The references themselves are passed by value to methods.
  • The = and == operators assign and test references.
  • Use clone() to copy an object
  • Use equals() to test that two different objects 'are equal' (have the same value)
  • The referencing and dereferencing is handled automatically by Java.
  • A reference type can never be cast to a primitive type
  • A primitive type can never be cast to a reference type
  • There is no pointer arithmetic in Java
  • There is no sizeof operator in Java
  • null is a special value that means 'no object' or 'absence of reference to object'.
 

This page was last modified on 02 October, 2007