Get startedGet started for free

Implementing memory-efficient string processing

You're developing a text processing application that needs to pre-populate an array with the same string value multiple times. The current implementation creates a new String object in each loop iteration, which is inefficient for large arrays. Your task is to implement a more efficient version of this method.

This exercise is part of the course

Optimizing Code in Java

View Course

Exercise instructions

  • Reuse the provided value to add to the list.
  • Return the final array.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class ArrayPopulation {
    
    public static void main(String[] args) {
        int size = 10000;

        String[] inefficientArray = populateArrayInefficient(size, "DataCamp");
        String[] efficientArray = populateArrayEfficient(size, "DataCamp");

        System.out.println("Arrays have same length: " + (inefficientArray.length == efficientArray.length));
    }

    public static String[] populateArrayInefficient(int size, String value) {
        String[] array = new String[size];
        
        for (int i = 0; i < size; i++) {
            String stringValue = new String(value);
            array[i] = stringValue;
        }
        
        return array;
    }

    public static String[] populateArrayEfficient(int size, String value) {
        String[] array = new String[size];
        
        for (int i = 0; i < size; i++) {
            // Reuse the same String object
            ____
        }
        
        // Return the final array
        return ____;
    }
}
Edit and Run Code