The Wayback Machine - https://web.archive.org/web/20241001003329/https://www.geeksforgeeks.org/how-to-initialize-an-array-in-java/
Open In App

How to Initialize an Array in Java?

Last Updated : 14 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An array is a data structure in Java that is used to store data objects having the same data type. Each and every element in an array has a unique index value. In an array, we have to declare its size first and the size of the array is fixed. In an array, we can store elements of different data types like integer, string, date and etc. In this article, we will discuss about different ways to declare and initialize an array.

Declaring an Array in Java

An array is declared by using its data type and identifier. In Java, arrays are declared in a similar way as other variables are declared but an extra bracket [] is added when we declare an array.

Syntax:

int arr [];
int [] arr;

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.

How to 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 can initialize an array with default or non-default values. Below are different methods to initialize an Array:

  • Initialize an Array with default values 
  • Initialize an Array with non-default values 
  • Initialize an Array using Curly braces { }
  • Initialization using stream Interface

Initialize an Array with 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];

 In the above code, an array of size 20 is declared where the data type is integer. Different data types have different default values which are initialized at the time of declaration. For integer type array default value is 0, false is the default value for boolean type array and empty string is the default value for string type array.

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.

In the following example, an integer type array of size 6 is declared and then 6 non-default values are initialized in it.

int[] arr = new int[6];
arr[0] = 8;
arr[1] = 6;
arr[2] = 4;
arr[3] = 2;
arr[4] = 1;
arr[5] = 9;

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.

In the following example, a string-type array is initialized with non-default values using curly braces.

String[] arrStr = {"Geeks", "of", "Geeks"};

Initialization using stream Interface

An array can be initialized by using a stream interface which generates a stream of values and then it is converted into an array. Below are three instream interfaces that are used to initialize an integer type array.

  • IntStream.range()
  • IntStream.rangeClosed()
  • IntStream.of()

1. IntStream.range()

It is used to initialize an array of integers within a given range. The first parameter in the range will be the first element of the array and the other elements in the array will be greater than that element but less than the second parameter of the range.

2. IntStream.rangeClosed()

We can also use rangeClosed() instead of range() if we want to add the last element of the range in an array. The first parameter in the rangeClosed() method will be the first element of the array and the other elements in the array will be greater than that element but less than and equal to the second parameter of the rangeClosed() method.

3. IntStream.of()

This method works similarly to curly braces where we have to mention each and every element individually that we want to assign to the array. In the following code, we have assigned values to the array by using these three interfaces.

Example:

Java




// Java program to demonstrate different ways of
// initializing an integer array.
import java.util.stream.IntStream;
  
// Driver Clas
public class Main {
    // Main function
    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] + " ");
        }
    }
}


Output

1 2 3 4 
1 2 3 4 
1 2 3 4 


Similar Reads

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 basically 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 similarl
8 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 InvalidParameterEx
3 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 program to creat
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
Initialize a static Map using Java 9 Map.of()
In this article, a static map is created and initialised in Java using Java 9. 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. Java 9 feature - Map.of() method In Java 9, Map.of() was introduced which is a convenient way to create instances of Map
2 min read
Initialize a static Map in Java using Double Brace Initialization
In this article, a static map is created and initialised in Java using Double Brace Initialization. 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. Double Brace Initialization In Double Brace Initialization: The first brace creates a new Anonymous
2 min read
Initialize a list in a single line with a specified value using Java Stream
Given a value N, the task is to create a List having this value N in a single line in Java using Stream. Examples: Input: N = 5 Output: [5] Input: N = GeeksForGeeks Output: [GeeksForGeeks] Approach: Get the value N Generate the Stream using generate() method Set the size of the List to be created as 1 using limit() method Pass the value to be mappe
2 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
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
Initialize a list in a single line with a specified value
Given a value N, the task is to create a List having this value N in a single line in Java using Collection Framework only. Examples: Input: N = 5 Output: [5] Input: N = GeeksForGeeks Output: [GeeksForGeeks] Approach: Get the value N Generate a Collection with a single value N using Collections.nCopies() method Store this collection as a List. Belo
1 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Article Tags :
Practice Tags :