CS 199 EMP

Hosted by Jackie Chan and Akhila Ashokan

Topics: More About References, Java Memory Management, Imports and Libraries

Today's Learning Objectives

  • More About References (Covered Throughout)

  • Java Memory Management

  • Imports and Libraries

Write code on the homepage or any playground on the site!
https://cs125.cs.illinois.edu/

Slides are on the course site!
https://cs199emp.netlify.app/

"Hey you're pretty, can I get your reference?"

Remember, references are not the objects themselves. To prove it, use this line of code.

Object o = new Object();
System.out.println(o);

Java will print out java.lang.Object@<memory address> which denotes the type, java.lang.Object, and it's location in memory.

Any variable with the same reference will manipulate the same object. New objects are only created through the new keyword.

Objects vs. Primitives Mutability

Mutability: The ability to change.

Objects are mutable, i.e. they can change after they're declared.

On the other hand, primitives (int, double, char) are immutable. Instead, primitives (and String) are replaced whenever reassigned.

int i = 5; // i stores 5.
i = 1; // 5 gets replaced by 1. 5 gets lost.

Pet myPet = new Pet("Josh"); // myPet stores a name containing "Josh".
myPet.name = "Justin";
// "Josh" gets replaced with "Justin", but the myPet is still the same.

"Who cares about mutability?"

It'll help you understand how functions deal with objects vs. primitives. Consider below.

void addOne(int i) { // takes a primitive.
  i++;
}

int age = 23;
addOne(age);
System.out.println(age); // still 23!

class Pet {
  String name;
  int age;

  Pet(String setName, int setAge) {
    this.name = setName;
    this.age = setAge;
  }
}

void addOne(Pet pet) {
  pet.age++;
}

Pet myPet = new Pet("Josh", 5); // .name and .age
addOne(myPet);
System.out.println(myPet.age); // it's now 6! (not factorial)

Practice with Mutability (10 minutes)

You just got hired by the TSA! Congrats!

You need to write a program to stamp passports given a Passport and ID object.

You will stamp the passport only if the name and age on both match on both forms.

Because objects are mutable, make this a void function that will change the passport itself.

Print out "Rejected!" if they don't match, otherwise print "Enjoy your flight!".

Passport Stamping Starter Code

class ID {
  String name;
  int age;

  ID(String setName, int setAge) {
    this.name = setName;
    this.age = setAge;
  }
}

class Passport extends ID {
  boolean stamped;

  Passport(String setName, int setAge) {
    super(setName, setAge);
  }
}

void stampPassport(Passport p, ID i) {
  // your code here.
}

Passport jackiePassport = new Passport("Jackie", 23);
ID jackieID = new ID("Jackie", 23);
ID strangerID = new ID("Josh", 27);

stampPassport(jackiePassport, jackieID); // should print "Enjoy your flight!"
System.out.println(jackiePassport.stamped); // should print "true".

stampPassport(jackiePassport, strangerID); // should print "Rejected!"

Java Memory Management

Java is a pioneer in memory management. It has a feature called automatic garbage collection which removes the responsibility of deleting memory from you.

Java will delete objects/variables when there are no more references pointing to it.

This is a blessing that you'll soon appreciate more when you continue your computer science journey—talk to anyone who's taken a C/C++ course about segfaults.

Questions On Memory (5 minutes)

  1. New objects are created in memory only when <keyword> is found in code.

  2. How big of a concern is memory for most instances of programming?

  3. How do you think about memory? How do you imagine how memory works on a computer?

"Don't reinvent the wheel dude." - Imports and Libraries

Let's say you want to program something that handles times. That's very annoying. You have to deal with multiple different timezones, formats (AM/PM, or 24 hour), daylight savings, conversions. Holy cow that's miserable. That's why you don't and import someone else's library.

More likely than not, someone has solved your problem more thoroughly than you. If it's available, use it and appreciate the fact that computer science is collaborative.

Fascinating video about how annoying timezones is in programming!

Some Java Libraries as Reminders

  • java.util.Random gets you a (psuedo-)random number (harder than you think)!

  • java.util.Arrays gets arrays with more functionality!

  • java.util.ArrayList gets ArrayList objects from Java!

  • java.math gets amazing math functions (e.g. exponents, sin/cos/tan, logs)!

Practice with Libraries (30 minutes)

We'll use java.util.ArrayList and java.util.Random.

We'll make a ArrayList of Marbles and use a variety of functions in provided by ArrayList.

  • Implement a function called void printBag(ArrayList<Marble> bagOfMarbles) that prints out all the marbles in the bag. (10 minutes)

  • Implement a function called void addAll(ArrayList<Marble> bagOfMarbles, Marbles[] marbles) to add all Marble objects in an array into the ArrayList. (10 minutes)

  • Implement a function called Marble pickRandom(ArrayList<Marble> bagOfMarbles) that will return a random, removed Marble from the given bag. (10 minutes)

ArrayList documentation and Random documenation.

Marbles Starter Code

import java.util.ArrayList;
// import java.util.Random;

class Marble {
  String color;
  int radius;
  
  Marble(String setColor, int setRadius) {
    this.color = setColor;
    this.radius = setRadius;
  }
}

ArrayList<Marble> bagOfMarbles = new ArrayList<Marble>();
bagOfMarbles.add(new Marble("Red", 1));
bagOfMarbles.add(new Marble("Red", 1));

That's it for today!

I didn't get to serialization today, but we'll touch more on it later I'm sure.

Hopefully these problems give you a better idea of how references work and how Java handles them differently than primitives.

Have a safe and fun weekend! Do something fun.

Solution Section

Passport Stamping Solution

void stampPassport(Passport p, ID i) {
  if (p.name.equals(i.name) && p.age == i.age) {
    System.out.println("Enjoy your flight!");
    p.stamped = true;
  } else {
    System.out.println("Rejected!");
  }

  return;
}

Memory Answers

  1. New objects are created in memory only when the new keyword is present.

  2. Memory shouldn't be a huge concern to most programmers. Exceptions include very low-powered devices or when performance is critical (like very critical). I don't consider it usually, I prioritize readability more.

  3. Memory, to me, is a long string of 1s and 0s that get allocated to you by a programming language/operating system (something you don't really need to consider). Whatever those 1s and 0s represent depends on context, but dividing up that memory for programs isn't something you need to consider as the programming languages/operating systems you're working with handle it.

Marbles Solution

void printBag(ArrayList<Marble> bagOfMarbles) {
  int size = bagOfMarbles.size();
  
  for (int i = 0; i < size; i++) {
    Marble m = bagOfMarbles.get(i);
    System.out.println(m.color + " marble, size: " + m.radius);
  }
  
  return;
}

Marbles Solution (Cont.)

void addAll(ArrayList<Marble> bagOfMarbles, Marble[] marbles) {
  for (int i = 0; i < marbles.length; i++) {
    bagOfMarbles.add(marbles[i]);
  }
  
  return;
}

Marbles Solution (Cont.)

Marble removeRandom(ArrayList<Marble> bagOfMarbles) {
  Random rand = new Random();
  int randomIndex = rand.nextInt(bagOfMarbles.size());
  
  Marble m = bagOfMarbles.get(randomIndex);
  bagOfMarbles.remove(randomIndex);
  
  return m;
}