Object Creation and Storage (Instantiation)
// Homework Hack #1: Object Creation Practice
public class ObjectCreation {
public static void main(String[] args) {
// 1. Create two Car objects using 'new'
Car car1 = new Car("Tesla", 2024);
Car car2 = new Car("Toyota", 2015);
// 2. Print each car's info
System.out.println(car1);
System.out.println(car2);
// (Optional) call another method
car1.honk();
car2.honk();
}
}
class Car {
// 1. Declare variables: brand, year
private String brand;
private int year;
// 2. Create a constructor to set those variables
public Car(String brand, int year) {
this.brand = brand;
this.year = year;
}
// 3. Add a method or toString() to display car info
@Override
public String toString() {
return "Car{brand='" + brand + "', year=" + year + "}";
}
// Extra method (optional)
public void honk() {
System.out.println(brand + " (" + year + ") says: Beep!");
}
}
Homework Hack #2 — Heap vs Stack Storage Demo
Goal - Understand where data is stored in memory — stack vs heap.
Instructions:
- Create a Book class with one variable: String title.
- In main(), create:
- A primitive variable (e.g. int pages = 300;)
- A Book object (e.g. Book b1 = new Book(“Java Basics”);)
- Copy both into new variables (int pagesCopy = pages;, Book b2 = b1;)
Change the original values and print everything — watch what changes.
// 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 = 300;
// 2. Create another primitive variable that copies it
int pagesCopy = pages;
// 3. Create a Book object
Book b1 = new Book("Java Basics");
// 4. Create another Book reference that points to the same object
Book b2 = b1;
// 5. Change the original primitive and the Book title
pages = 450; // changes ONLY 'pages', not 'pagesCopy'
b1.setTitle("Advanced Java"); // mutates the single Book object on the heap
// 6. Print both sets of values to compare behavior
System.out.println("Primitives (copied by value):");
System.out.println("pages: " + pages); // 450
System.out.println("pagesCopy: " + pagesCopy); // 300
System.out.println("\nObject references (aliases to same heap object):");
System.out.println("b1: " + b1);
System.out.println("b2: " + b2);
// Show they are the same object
System.out.println("\nAre b1 and b2 the same object? " + (b1 == b2));
}
}
class Book {
// 1. Declare variable: String title
private String title;
// 2. Create a constructor to set the title
public Book(String title) {
this.title = title;
}
// Mutator to change title (so we can demonstrate shared reference changes)
public void setTitle(String newTitle) {
this.title = newTitle;
}
// 3. Create a toString() to show the title
@Override
public String toString() {
return "Book{title='" + title + "'}";
}
}