How do I declare and initialize a new array in Java?

I need to create an array in Java and initialize it with values. What are the different ways to declare and initialize a Java new array, and which approach is best for different use cases?

Alright, so if you’re just getting started, the simplest way to declare and initialize a java new array would look like this:

int[] numbers = {1, 2, 3, 4, 5};

This inline initialization is ideal when you already know the values ahead of time. But let’s say you want to declare the array first and then fill it later. You could do something like this:

int[] numbers = new int[5];  
numbers[0] = 1;  
numbers[1] = 2;  
// ... and so on

This approach works great when the values will be dynamically assigned, maybe from user input or some calculations.

Nice one, Joe! Now, if you want to level up and use a more modern, flexible way, I’d recommend using Java 8+ Streams to initialize your java new array. For example:

int[] numbers = java.util.stream.IntStream.range(1, 6).toArray();

This creates an array of values from 1 to 5 without manually specifying each element, making it ideal when you need more dynamic or calculated values. But let’s say you need to fill an array with the same value—here’s a way to do that too:

int[] filledArray = java.util.Collections.nCopies(5, 10)
                .stream().mapToInt(Integer::intValue).toArray();

This will give you an array like [10, 10, 10, 10, 10]. It’s a slick way of handling repeated values, especially for larger arrays where you don’t want to write out each individual element.

Those are some great approaches, Richaa! But what if you need to start with a java new array and later change the values dynamically or even resize it? That’s where tools like Arrays.fill and Arrays.copyOf come in handy.

For example, if you want to initialize all elements of an array to the same value, you could do this:

int[] numbers = new int[5];  
java.util.Arrays.fill(numbers, 7);  // All elements set to 7

Now, if you want to expand your array after it’s been created, Arrays.copyOf is your friend. Here’s an example:

int[] original = {1, 2, 3};  
int[] expanded = java.util.Arrays.copyOf(original, 5);

This will create an array like [1, 2, 3, 0, 0], expanding the original array and maintaining its initial values. This is super helpful when you start with an array and need to adjust its size down the line, especially when dealing with resizable collections that are built on top of arrays.