int array

How to populate a Java int array with a range of values

I just learned an easy way to populate/initialize a Java int array with data, such as a range of numbers. The key is to use the rangeClosed method on the Java 8 IntStream class. Here’s an example using the Scala REPL:

scala> val n =, 10).toArray()
n: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

I show that in Scala to show the output, and here’s what it looks like with Java:

Java ‘int’ array examples (declaring, initializing, populating)

Java array FAQ: How do you create an array of Java int values (i.e., a Java “int array”)?

Answer: There are several ways to define an int array in Java; let’s take a look at a few examples.

1) Declare a Java int array with initial size; populate it later

If you know the desired size of your array, an you'll be adding elements to your array some time later in your code, you can define a Java int array using this syntax: