References Example


/* This is a primitive */
int x = 127;

/* This is a reference */
String s = new String("Hello");

Arrays are Reference Types


/* This is an array */
int[] x = {5,7,8};

Using == on references


/* What do you think this does? */
Date date1 = new Date(2018, 6, 14);
Date date2 = new Date(2018, 6, 14);

if(date1 == date2){
  System.out.println("They are the same!");
}

Using == on references


/* These two vars are NOT == */
Date date1 = new Date(2018, 6, 14);
Date date2 = new Date(2018, 6, 14);

if(date1 == date2){
  System.out.println("They are the same!");
}

Comparing references


/* These two vars are NOT == */
Date date1 = new Date(2018, 6, 14);
Date date2 = new Date(2018, 6, 14);

/* Use .equals() to compare references */
if(date1.equals(date2)){
  System.out.println("They are the same!");
}

Assignment of References


Date date1 = new Date(2018, 6, 14);
Date date2 = new Date(2018, 7, 18);

date1 = date2;

System.out.println(date1);

Assignment of References


Date date1 = new Date(2018, 6, 14);
Date date2 = new Date(2018, 7, 18);

date1 = date2;

System.out.println(date1);

Before the assignment

Assignment of References


Date date1 = new Date(2018, 6, 14);
Date date2 = new Date(2018, 7, 18);

date1 = date2;

System.out.println(date1);

AFTER the assignment

Shared References


/* From previous slide */
/* Note that BOTH date1 and date2 are changed */
date1.setYear(2017)

Another Example of References


/* From previous slide */
/* Note that date1 is not affected here */
date2 = new Date(2013, 10, 28);