Old Information is Lost

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        

Will the following statement make the array larger?

list = new String[5];

Answer:

No. The statement creates a completely new array object (with 5 cells). The old array object is now garbage, unless some other reference variable points to it.

Old Information is Lost

old array and new array

 

In the example, the reference variable list is set to the newly constructed object. The diagram shows what happens. The diagonal slashes represent null, the value that means "no object".

The information in the old object is not transferred to the new object. To keep the old information, the program would have to copy it to a new array after it was constructed. This is not too hard, but it is a nuisance.

QUESTION 3:

What happens if information is added to an array slot that does not exist?

String[] list = new String[3];
list[0] = "ant" ;
list[1] = "bat" ;
list[2] = "cat" ;

list[3] = "dog" ;