Mar 05: Memory Diagrams
Learning Objectives
After today's class, you should be able to:
- Describe primitive values and references in a memory diagram.
- Draw memory diagrams that have variables, arrays and objects.
- Summarize differences between variables, arrays, and objects.
Reminders¶
On the Board¶
Memory Diagrams – how to draw pictures like Java Visualizer
Exercise 1: Variables
long money = 50;
boolean good = true;
double price = money;
char hash = '#';
String rating = "PG";
Exercise 2: Arrays
int[] data = null;
int[] counts = {10, 3, 7, -5};
double[] scores = new double[3];
String[] words = new String[2];
String[] take = {"CS 159", "CS 227"};
int[] easy = {1, 2, 3};
int[] copy = easy;
Exercise 3: Methods
public static void main(String[] args) {
int[] nums = {159, 227};
printArray(nums);
}
public static void printArray(int[] a) {
System.out.print("{" + a[0]);
for (int i = 1; i < a.length; i++) {
System.out.print(", " + a[i]);
}
System.out.println("}");
}
Exercise 4: Objects
public class Card {
private int rank; // 1=Ace, ..., 11=Jack, 12=Queen, 13=King
private int suit; // 0=Clubs, 1=Diamonds, 2=Hearts, 3=Spades
public Card(int rank, int suit) {
this.rank = rank;
this.suit = suit;
}
public static void main(String[] args) {
Card c1 = new Card(8, 1);
Card c2 = new Card(12, 2);
Card c3 = c1;
c1 = c2;
}
}
Exercise 5: Static
public class BankAccount {
private static final String PREFIX = "1234";
private static int nextNumber = 1;
private String number;
private String owner;
private double balance;
public BankAccount(String owner) {
this.number = PREFIX + String.format("%04d", nextNumber);
this.owner = owner;
nextNumber++;
}
public static void main(String[] args) {
BankAccount ba1 = new BankAccount("Stacie");
BankAccount ba2 = new BankAccount("Trevor");
}
}