Java Tutorials Test






Java Fundamentals 2


Language Fundamentals Part 2


Table of Contents

Section Objectives

  • Understand object references in Java and how they differ from primitive variables
  • Understand strings in Java
  • Learn how to create and use arrays
  • Understand the primitive wrapper classes and their uses

Object References

Variables – Review
  • Primitive variable – stores a data value directly

  • Reference variable – stores a reference to an object

int i = 13; //i is a primitive variable that holds the value 13
Person p = new Person(); //p is a reference or handle to a Person

Diagram

With primitives, there is only one thing created in memory.
– i is a memory location that holds the value 13.

With objects, two things are created in memory.
– The object itself, as well as a reference to the object.
– p is a memory location that points to the actual Person object.
– All reference variables are 32-bits in size. They are physical things in memory, like primitive variables.

You can think of a reference variable as a “remote control” for an object, similar to the one for your TV at home.
– It has “operation buttons” on it, and when you push them, “messages” get sent to the object, where the operations are actually performed.


Object Identity
  • Recall that with primitives == tests for equality
  • Indicates if two values are equal or the same
int x = 3;
boolean xIs3 = (x == 3);  // true
  • With reference variables == tests for identity
    – Indicates if two references point to the same object
Turtle t1 = new Turtle();  // brand new Turtle
Turtle t2 = new Turtle();  // brand new Turtle

Turtle t3 = t2;            // t3 refers to same Turtle object as t2
t1 == t2    // false
t3 == t2    // true

Diagram2


null
  • Indicates that a reference variable doesn’t point to an object

  • Can test references for null

Turtle t;                       // no new means no object, t is null
boolean tIsNull = (t == null);  // true
  • Can explicitly initialize to null
Turtle t = null;
  • Can’t call methods on null references
    – There’s no object to execute the code
    – Results in NullPointerException
    Diagram2

Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character