Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Declare an Array in Java?
Next article icon

How to Declare and Initialize an Array in Java?

Last Updated : 28 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An array in Java is a linear data structure that is used to store multiple values of the same data type. In an array, each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java. In an array, we can store elements of different data types like integer, string, character, etc.

In this article, we will discuss different ways to declare and initialize an array in Java.

1. Basic Array Declaration and Initialization

Declare an Array in Java

Understanding how to declare an array in Java is very important. In Java, an array is declared by specifying its data type, an identifier, and adding brackets [] to indicate it is an array.

Syntax

type arrayName [];
type [] arrayName;

  • type: The type of elements the array will hold (e.g., int, String).
  • arrayName: The name of an array.

Here, the size of the array is not mentioned because a reference to an array is created in memory. It can also be known as the 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 with other variables. In an array, we have to assign multiple values, so the initializing process is not as simple as with 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 with default values when the size of the array is declared with square 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


2. 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.

1. Using IntStream.range()

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


2. Using IntStream.rangeClosed()

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


3. Using IntStream.of()

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


Implementation

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 Geeks {       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 

Next Article
How to Declare an Array in Java?

A

ayushdey110
Improve
Article Tags :
  • Java
  • Java-Arrays
Practice Tags :
  • Java

Similar Reads

    How to Initialize an Array in Java?
    An array in Java is a linear data structure that is used to store multiple values of the same data type. In an array, each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java
    5 min read
    How to Declare an Array in Java?
    In Java programming, arrays are one of the most essential data structures used to store multiple values of the same type in a single variable. Understanding how to declare an array in Java is very important. In this article, we will cover everything about array declaration, including the syntax, dif
    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 containi
    5 min read
    How to initialize an array in JavaScript ?
    Initializing an array in JavaScript involves creating a variable and assigning it an array literal. The array items are enclosed in square bracket with comma-separated elements. These elements can be of any data type and can be omitted for an empty array.Initialize an Array using Array LiteralInitia
    3 min read
    Initialize an ArrayList in Java
    ArrayList is a part of the 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 the AbstractList class and imp
    4 min read
    How to Add an Element to an Array in Java?
    In Java, arrays are of fixed size, and we can not change the size of an array dynamically. We have given an array of size n, and our task is to add an element x into the array. In this article, we will discuss the NewDifferent Ways to Add an Element to an ArrayThere are two different approaches we c
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences