CS2514

Introduction to Java

Dr Derek Bridge

School of Computer Science & Information Technology

University College Cork

Primitive types and reference types

They hold different kinds of things

Arrays

Arrays of reference types

Dog[] my_sled_team = null;
Array is null
my_sled_team = new Dog[3];
Array of nulls
my_sled_team[0] = new Dog("Charles", 2, "Charlywawa");
my_sled_team[1] = new Dog("Charlene", 7, "Charlywawa");
Array of references

Printing the contents of a variable

Assignment copies contents

int x = 10;
int y = x;
x contains 10, so a copy of this value is put into y
Dog myDog = new Dog("Nobby", 3, "Norfolk Long Pig");
Dog yourDog = myDog;
myDog contains a reference, so a copy of this reference is put into yourDog, giving two references to the same object (not two objects)

Consequences

Equality testing using == compares contents

int x = 10;
int y = x;
int z = 10;
if (x == y) {
    System.out.println("Yes, x == y");
}
if (x == z ) {
    System.out.println("Yes, x == z");
}

String s1 = "Hi";
String s2 = s1;
String s3 = "Hi";
String s4 = new String("Hi");
if (s1 == s2) {
    System.out.println("Yes, s1 == s2");
}
if (s1 == s3) {
    System.out.println("Yes, s1 == s3");
}
if (s1 == s4) {
    System.out.println("Yes, s1 == s4");
}

Dog d1 = new Dog("Nobby", 3, "Norfolk Long Pig");
Dog d2 = d1;
Dog d3 = new Dog("Nobby", 3, "Norfolk Long Pig");
if (d1 == d2) {
    System.out.println("Yes, d1 == d2");
}
if (d1 == d3) {
    System.out.println("Yes, d1 == d3");
}

Using a method instead of ==

Defining an equals method

Summary

Primitive typesReference types
Examples
int, double, boolean arrays, String, Scanner, Dog
Contents
Contains a value Contains null or a reference ('pointer') to an object
System.out.println(...)
Displays the value Runs toString. By default, toString displays the pointer. But you can supply your own definition to display something more meaningful
Assignment
Copies the value Copies the reference (hence two pointers to the same object)
Equality testing
== tests for equal values
  • == tests for equal references (pointing to the same object
  • define your own equals method to compare the objects' instance variables
Passing a parameter to a method
Copies the value, so changes made in the method do not affect the original Copies the reference (hence two pointers to the same object), so changes to the object made in the method do affect the original

Advanced stuff: Python

Java's wrapper classes