- Forward


Objects and References
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review of Data Types in Java
Back SMYC Forward
  • Primitive (a.k.a. Atomic or Fundamental) Types:
    • Types like boolean, double, int,... that don't have constituent parts
  • Reference Types:
    • Types like classes and arrays
Type Handling in General
Back SMYC Forward
  • Primitive Types:
    • Identifier/Name
    • Primitive Value
  • Reference Types:
    • Identifier/Name
    • Reference (The terms "reference", "memory address", and "pointer" are often used interchangeably. Be aware that there can be important differences.)
    • Nerd Humor
      comics/DinosaurComics-Pointers.png
      (Courtesy of Dinosaur Comics)
      Expand
A Special Reference
Back SMYC Forward
  • An Observation:
    • It is often convenient to differentiate a reference variable that has been initialized from one that has not
  • The Reference null:
    • null can be used to indicate that a reference variable does not refer to anything
The . Operator
Back SMYC Forward
  • Purpose:
    • Object "membership"
  • Internally:
    • Performs address arithmetic
Some Java Internals
Back SMYC Forward

An Example of a Primitive Type
(A Fragment of main())

javaexamples/basics/MemoryAllocationExample1.java (Fragment: 0)
 
Some Java Internals (cont.)
Back SMYC Forward

An Example of a Reference Type
(A Fragment of main())

javaexamples/basics/MemoryAllocationExample1.java (Fragment: 2)
 
Memory Allocation
Back SMYC Forward
  • In Reality:
    • Memory allocation in Java is complicated, has changed over time (e.g., from the PermGen section to the MetaSpace section), and is handled by the Java Virtual Machine (JVM) and can vary with the JVM
  • For Our Purposes:
    • We will use a simpler model
A Conceptual Model of Memory
Back SMYC Forward
  • Name Table:
    • Holds information that available at compile-time (e.g., declarations of local variables, parameters, class names)
  • Heap:
    • Holds information that is determined at run-time when the new operator is invoke
  • Class Space:
    • Holds information about the static attributes of classes
  • Literal Space:
    • To save memory, Java "interns" String literals (i.e., it stores only one copy of a specific String)
The new Operator and Memory
Back SMYC Forward
  • What It Does for Objects:
    • Allocates (a contiguous block of) memory to hold all of the non-static attributes
    • Invokes the constructor (that is its right-side operand)
  • What It Does for Arrays:
    • Allocates (a contiguous block of) memory to hold all of the elements
    • Initializes all of the elements
    • Assigns a value to the (final) length attribute at that address
  • What It Evaluates To:
    • The address of the memory that is allocated
Visualization of Memory
Back SMYC Forward
images/JavaMemoryModel.png

Note About the Heap, Literals space, and Class space: We will sometimes worry about the size of entities and work directly with the bytes and will sometimes work with larger entities and not worry about the bytes they occupy.

An Example of Static Memory Allocation
Back SMYC Forward

In this example (from a fragment of main()), the same memory is used for the variables during each iteration.

javaexamples/basics/MemoryAllocationExample2.java (Fragment: 0)
 
An Example of Static Memory Allocation (cont.)
Back SMYC Forward
images/JavaMemoryModel_StackExample.png
An Example of Static and Dynamic Memory Allocation
Back SMYC Forward

In this example (from a fragment of main()), memory is allocated for a Color object each iteration. (Reminder: A Color object has three int attributes, named red, green, and blue.)

javaexamples/basics/MemoryAllocationExample4.java (Fragment: 0)
 
An Example of Static and Dynamic Memory Allocation (cont.)
Back SMYC Forward
images/JavaMemoryModel_HeapExample.png

Note: In this example we are not worrying about the size of the three int attributes in the Color objects.

Assignment
Back SMYC Forward
  • Assignment in General:
    • Assign what is on the right-hand-side of the operator to the variable on the left-hand-side
  • With Value Types:
    • The left-hand-side variable contains a a value
    • The right-hand-side must be a value
  • With Reference Types:
    • The left-hand-side variable contains an address
    • The right-hand-side must be an address
    • The assignment process is sometimes referred to as "binding" a particular object to a variable
Assignment to final Variables
Back SMYC Forward
  • final Variables:
    • The compiler ensures that the variable can only be initialized once
  • With Value Types:
    • The behavior is as expected
  • With Reference Types:
    • The behavior might be surprising - a reference can only be assigned to the variable once, but values/references can be assigned to the attributes of the object being referred to multiple times
Reference Variables Declared to be final
Back SMYC Forward

Consider the following class:

javaexamples/basics/Pair.java (Fragment: 0)
 

And the following fragment (in main()):

final Pair p; p = new Pair(); p.a = 0; p.b = 100; // This line will compile p.a = 50; // This line will not compile p = new Pair();
Aliases
Back SMYC Forward

The following example (from a fragment of main()) uses the assignment operator both during the instantiation of an object and to create an alias.

javaexamples/basics/AkaExample1.java (Fragment: 0)
 
Aliases (cont.)
Back SMYC Forward
javaexamples/basics/Pair.java (Fragment: 0)
 

In the following example (from a fragment of main()), p and q refer to the same object so changing the attributes of one changes the attributes of "the other".

javaexamples/basics/AkaExample3.java (Fragment: 0)
 
Copies of an Object
Back SMYC Forward
  • Different Situations:
    • Sometimes you want two variables to refer to the same object (i.e., aliases)
    • Sometimes you want two variables to (initially) refer to copies of the same object
  • Kinds of Copies:
    • Shallow Copy - When an object has an attribute that is a reference type, only the reference is copied (i.e., the copy contains an alias of the attribute)
    • Deep Copy - When an object has an attribute that is a reference type, a (deep) copy of the attribute is made
Aliases, Shallow Copies and Deep Copies
Back SMYC Forward
public class Customer { public int id; } public class Account { public Customer holder; public double balance; }
Account a, d, s, o; Customer wilma; // Instantiate the Customer wilma = new Customer(); wilma.id = 1; // Instantiate the original Account object o = new Account(); o.holder = wilma; o.balance = 100.00; // a is an alias for o a = o; // s is a shallow copy of o s = new Account(); s.holder = o.holder; s.balance = o.balance; // d is a deep copy of o d = new Account(); d.holder = new Customer(); d.holder.id = o.holder.id; d.balance = o.balance;
Comparing Reference Types
Back SMYC Forward

The relational equals operator (i.e., ==) can be used with reference types, and it is sometimes necessary to do so, but you must understand that it compares two references.

javaexamples/basics/AkaExample2.java (Fragment: 0)
 
Comparing Reference Types (cont.)
Back SMYC Forward
  • What We Just Learned:
    • When used with reference types, the == operator compares references
  • Suppose We Want to Compare the Attributes:
    • Well-designed classes include a .equals() method for this purpose
javaexamples/basics/AkaExample2.java (Fragment: 1)
 
A Note About String Literals
Back SMYC Forward

String literals are reference types, but the compiler can be smart and store only one instance of each (a process called "interning").

String s, t, u; s = "James Madison University"; t = s; u = "James Madison University"; // This will, not surprisingly, print "Same contents" if (s.equals(u)) System.out.println("Same contents"); // This will, not surprisingly, print "Same reference" if (s == t) System.out.println("Same reference"); // This may, somewhat surprisingly, print "Same reference" // but you shouldn't rely on it if (s == u) System.out.println("Same reference");
A Note About the "null String"
Back SMYC Forward

Since String objects are reference types, a String variable can contain the reference null.

String s; s = null;

This is not the same thing as what is sometimes called the "null String" (and sometimes, perhaps less ambiguously, called the "empty String").

String t; t = "";
A Note About Static Attributes
Back SMYC Forward

Consider the following example:

double unitCircumference; unitCircumference = 2.0 * Math.PI;

and recall that the Math class has two static double attributes, E and PI.

A Note about Static Attributes (cont.)
Back SMYC Forward
images/JavaMemoryModel_StaticAttributeExample.png
Unused/Unwanted Memory
Back SMYC Forward
  • Some Other Languages:
    • Unwanted memory needs to be deallocated (i.e., returned to the memory heap)
    • Objects need to be "destroyed" (by calling their destructor)
  • Java:
    • Has a garbage collector
Garbage Collection
Back SMYC Forward
  • Garbage and "Leaked" Memory:
    • Memory that is no longer referenced by any variable
  • Garbage Collection:
    • Automatically returning garbage to the memory heap
An Example Revisited: Garbage Collection
Back SMYC Forward

Note that the address of c changes every iteration. Hence the memory that was allocated in the previous iteration becomes garbage.

javaexamples/basics/MemoryAllocationExample4.java (Fragment: 0)
 
A Brief Discussion of Arrays
Back SMYC Forward
  • An Important Point:
    • Arrays are reference types (in Java)
  • Questions for Another Lecture:
    • What happens in each of the following statements?
    • int[] scores;
    • scores = new int[3];
    • scores[0] = 5;

    • Student[] cs149;
    • cs149 = new Student[3];
    • cs149[0] = new Student("Barney","Rubble");
There's Always More to Learn
Back -