Popcorn Hack 1

  1. Why does changing b not affect a, but changing array2 affects array1? b and a are primitive values meaning that their values are directly stored in the variable. However, for array2 and array1, they store a pointer that reference a point in memory.

  2. Describe what’s on the stack vs. the heap for this code. Stack memory stores primitive variables while heap memory is stored in dynamic memory.

Popcorn Hack 2

  1. 21
  2. Still age 21
  3. Both ages are still referencing the same thign

Homework Hack 1

public class ObjectCreation {
    public static void main(String[] args) {
        Car car1 = new Car("Tesla", 2024);

        System.out.println(car1);
    }
}

class Car {
    // 1. Declare variables: brand, year
    private String brand;
    private int year;

    // 2. Create a constructor to set those variables
    Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    // 3. Add a method or toString() to display car info
    public void displayInfo() {
        System.out.println(brand);
        System.out.println(year);
    }
}

Car car1 = new Car("Tesla", 2024);
car1.displayInfo();

Tesla
2024

Homework Hack 2

// Homework Hack #2: Heap vs Stack Storage Demo

public class HeapVsStack {
    public static void main(String[] args) {
        // 1. Create a primitive variable (int pages)
        int pages = 100;
        
        // 2. Create another primitive variable that copies it
        int length = pages;
        
        // 3. Create a Book object (Book b1 = new Book("Java Basics");)
        Book b1 = new Book("Java Basics");
        
        // 4. Create another Book reference (Book b2 = b1;)
        Book b2 = b1;
        
        // 5. Change the original primitive and the Book title
        pages = 300;
        b1.bookTitle = "Return";
        
        // 6. Print both sets of values to compare behavior
        b1.printTitle();
        System.out.println("Book 1 pages: " + pages);
        b2.printTitle();
        System.out.println("Book 2 pages: " + length);
    }
}

class Book {
    // 1. Declare variable: String title
    public String title;
    public String bookTitle;
    
    // 2. Create a constructor to set the title
    Book(String title) {
        this.bookTitle = title;
    }

    public void setTitle(String newTitle) {
        this.bookTitle = newTitle;
    }
    
    // 3. Create a toString() to show the title
    public void printTitle() {
        System.out.println("The title of the book is " + this.bookTitle);
    }
}

HeapVsStack.main(null);
The title of the book is Return
Book 1 pages: 300
The title of the book is Return
Book 2 pages: 100