How to Initialize an Array in Java?
Last Updated :
25 Nov, 2024
An array in Java is a data structure used to store multiple values of the same data type. Each element in an array has a unique index value. It makes it easy to access individual elements. In an array, we have to declare its size first because the size of the array is fixed. In an array, we can store elements of different data types like integer, string, date, etc. In this article, we will discuss different ways to declare and initialize an array in Java.
Declare an Array in Java
In Java, an array is declared by specifying its data type, and identifier, and adding brackets [] to indicate it is an array.
Syntax to Declare an Array
type arrayName [];
type [] arrayName;
type: The type of elements the array will hold (e.g., int, String).arrayName: The name of an array.
Here, size of the array is not mentioned because a reference of an array is created in the memory. It can be also known as a memory address of an array.
Initialize an Array in Java
After declaring an array we have to initialize it with values as we have to do it with other variables. In an array, we have to assign multiple values, so the initializing process is not as simple as variables. We will cover the different ways to initialize arrays below.
1. Initialize an Array with a Fixed Size and Default Values
In Java, an array can be initialized by default values when the size of the array is declared with rectangular brackets [ ].
int [] arr = new int[20]; // Array of size 20, initialized with default values (0)
We can specify the size of an array at the time of initialization. When we created this way, each element gets a default value (0 for integers, false for boolean, and null for objects).
2. Initialize an Array with Specific Values
When we know the values and we want to store it, we can initialize the array with specific values directly.
int[] arr = {1, 2, 3, 4, 5}; // Array initialized with specified values
3. Initialize an Array Using Curly Braces { }
An array can also be initialized by using curly braces where we don’t have to declare the size of the array. All the non-default values are initialized in the curly braces which are separated by a comma.
String[] arr = {“Geeks”, “of”, “Geeks”};
In the above example, a string-type array is initialized with non-default values using curly braces.
4. Initialize an Array with non-default values
In Java, we can also initialize an array with particular values. For that, we need to initialize each value one by one. But this method is only useful for small sizes of arrays not for arrays having large sizes. For large-size arrays, we have to use a loop to initialize non-default values.
int[] arr = new int[4];
arr[0] = 2;
arr[1] = 4;
arr[2] = 6;
arr[3] = 8;
In the above example, an integer type array of size 4 is declared and then 4 non-default values are initialized in it.
5. Initializing an Array Using Loops
We can also use loops to initialize array elements with specific values. This method is specially useful for larger arrays.
Example:
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1; // Fills array with values 1, 2, 3, 4, 5
}
Using Arrays with Unknown Size
If the size of the array is unknown but we want to fill it dynamically, we can initialize it first with a fixed size and add values later or use a data structure like ArrayList. Some common operations are mentioned below:
Accessing Array Elements Using Index
We can access and manipulate array elements by referring to their index.
int[] arr = {1, 2, 3, 4};
System.out.println(arr[0]); // Output: 1
Using Array Length
We can use the length property to return the number of elements in an array.
int[] arr = {1, 2, 3, 4};
System.out.println(“Array length: ” + arr.length); // Output: 4
Advanced Initialization Using Streams
An array can be initialized by using a stream interface. The IntStream interface in Java offers additional ways to initialize arrays with sequential or predefined values. Below are three instream interfaces that are used to initialize an integer type array.
It is used to initialize an array of integers within a given range.
- The first parameter is the starting element.
- And the second parameter defines the upper limit (exclusive).
- It means the array will include elements greater than or equal to the first parameter but less than the second one.
Example:
int[] arr1 = java.util.stream.IntStream.range(1, 5).toArray();
// Output: 1 2 3 4
It creates an array within a range (inclusive of the end).
Example:
int[] arr2 = java.util.stream.IntStream.rangeClosed(1, 4).toArray();
// Output: 1 2 3 4
It directly initializes an array with specified values.
Example:
int[] arr3 = java.util.stream.IntStream.of(1, 2, 3, 4).toArray();
// Output: 1 2 3 4
Example Program
Below is a simple program demonstrating different ways of initializing an array.
Java
// Java program to demonstrate different ways of
// initializing an integer array
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// an array of integers using IntStream.range()
// method
int[] arr1 = IntStream.range(1, 5).toArray();
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
System.out.print('\n');
// an array of integers using
// IntStream.rangeClosed() method
int[] arr2 = IntStream.rangeClosed(1, 4).toArray();
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
System.out.print('\n');
// an array of integers using IntStream.of()
// method
int[] arr3 = IntStream.of(1, 2, 3, 4).toArray();
for (int i = 0; i < arr3.length; i++) {
System.out.print(arr3[i] + " ");
}
}
}
Output1 2 3 4
1 2 3 4
1 2 3 4
Kickstart your Java journey with our online course on Java Programming, covering everything from basics to advanced concepts. Complete real-world coding challenges and gain hands-on experience. Join the Three 90 Challenge—finish 90% in 90 days for a 90% refund. Start mastering Java today!
Similar Reads
How to Fill (initialize at once) an Array in Java?
An array is a group of like-typed variables that are referred to by a common name. In this, article we will learn about Filling array in Java while Initialization.Example:Java// Java program to fill the element in an array import java.util.*; public class Geeks { public static void main(String args[]) throws Exception { int a[] = new int[10]; // Ad
3 min read
Different Ways To Declare And Initialize 2-D Array in Java
An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is an array of arrays. A very common example of a 2D Array is Chess Board. A chessboard is a grid containing 64 1x1 square boxes. You can similarly visualiz
5 min read
Initialize HashMap in Java
HashMap in Java is a part of the java.util package and allows storing key-value pairs. Initializing a HashMap can be done in multiple ways, including static blocks, utility methods from the Collections class, and modern approaches provided by Java 8 and Java 9. This article will guide you through these methods with clear examples and explanations.
4 min read
Initialize an ArrayList in Java
ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.ArrayList inherits AbstractList class and implements List interface.ArrayList is initialized by a size,
3 min read
KeyPairGenerator initialize() method in Java with Examples
initialize(int keysize) The initialize() method of java.security.KeyPairGenerator is used to initialize KeyPairGenerator object for further use. Syntax: public void initialize(int keysize) Parameters: This method seeks keysize of int type as a parameter.Return Value: This method has nothing to return.Exception: This method throws InvalidParameter
3 min read
Java Program to Allocate and Initialize Super Class Members Using Constructor
A constructor in Java is a special method that is used to initialize an object. Whenever an object is created using the new keyword at least one construction is called. The constructor name must match with the class name and cannot have a return type. If there is no constructor available in the class in such a case java compiler provides a default
4 min read
How to Initialize and Compare Strings in Java?
String is one of the most basic data types and it is widely used in storing and manipulating pieces of text. One of the fundamental features of strings in Java is their immutability that is once a string is created, it will never be changed. Immutability creates two general ways of initialization with strings in Java using the String Pool. This art
5 min read
How to Initialize a Vector with a Specific Initial Capacity in Java?
In Java, Vector Class allows to creation of dynamic arrays that can grow or shrink as per the need. If we know the approximate size of elements, we will store this in the vector. Then we optimize memory usage, and we can initialize it with the specific initial capacity. In this article, we will learn how to initialize a Vector with a specific initi
2 min read
Initialize a static map in Java with Examples
In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Method 1: Creating a static map variable. Instantiating it in a static block. Below is the implementation of the above approach: Java // Java program to
1 min read
Initialize a static Map using Stream in Java
In this article, a static map is created and initialized in Java using Stream. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Stream In Java Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of
2 min read