Garbage

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

String alpha = new String("Red Rose") ;

alpha = null;

. . .
  1. Where is an object constructed?
    • In the first statement.
  2. What becomes of that object?
    • It became garbage in the second statement.

Garbage

garbage

The first statement does two things: (1) a String object is created, containing the characters "Red Rose". Then, (2) a reference to that object is saved in the reference variable alpha.

The second statement assigns the value null to alpha. When this happens, the reference to the object is lost. Since there is no reference to the object elsewhere, it is now garbage.

The line through the box in the second statement symbolizes the null value. The object still exists in memory. The memory it consists of will eventually be recycled by the garbage collector and will be made available for new objects.

QUESTION 7:

Examine this (slightly altered) snippet of code:

String alpha = new String("Red Rose");
String beta  = alpha;
alpha = null;

. . .
  1. Where is an object created?
  2. What happens in the second statement?
  3. What becomes of that object?