• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Array » What is Array in Java? – Definition, Declare, Create, Initialize [Example]
Next →
← Prev

What is Array in Java? – Definition, Declare, Create, Initialize [Example]

By Dinesh Thakur

Arrays Definition: Perhaps one of the most important of all concepts that you need to learn to be effective is the array. Until now, we have looked at variables that hold just one value – the ints hold one number and the strings hold one text string. Arrays are used when we want to hold two or more values, perhaps a list. Arrays can be thought as columns in a spreadsheet – a spreadsheet can have one, or it can have many columns.  

Similar to the spreadsheet, each row in an array has a position number; these begin at 0 and go up for each position that has a value. Setting up an array requires that you inform Java what type of data is being stored in it – strings, Booleans, integers,  and so on. Then you need to tell Java the number of positions in the array and do  this to set them up:

There is only one difference between setting up an int variable, and an array – the data type in an array is followed by square brackets []. These brackets are enough for Java to know that an array is being set up.

For example, To sort, maintain and display the marks of 80 students in a class, we need to declare 80 integer variables each of which holds the marks of a particular student. It is complicated to make and handle such a program that declares 80 int type variables, assign values to them and compare each against the other to do the sorting. The problem worsens if we have 1000 students. However, these types of problems can be simplified using arrays.

An array is a collection of logically related variables (similar elements) of the identical data type that share a common name. The array is a predefined class present in java.1ang package. It is a final class which can’t be inherited. It is used to handle a large amount of data, without the need to declare many individual variables separately. The array elements are stored in a contiguous memory location (i.e. one after the other). All the array elements must be either of any primitive types like int, float, char, double, etc. or they can be of any object references type like class.
Each array element is accessed and manipulated using an array name followed by a unique index or subscript that specify the position within the array. A single subscript is required to access an element of the one-dimensional array, and two subscripts are required to access an element of the two-dimensional array. All the arrays whose elements are accessed using two or more subscript are called multidimensional arrays. It should be kept in mind that each subscript is enclosed in square brackets and it should be expressed as a non-negative integer constant or expression. The primary advantage of an array is that it organises data in such a way that it can be manipulated. So if an array containing marks of students is given, then we can easily calculate the average marks scored by the students.

The concept of an array that helps us to store a group of values under a single name and refer directly to a particular value makes the programs very simple and efficient. This concept is present in almost all programming languages including C, c++ and Java.

We’ll be covering the following topics in this tutorial:

  • Creating Array
  • Declaring an Array
  • Instantiating an Array
  • Accessing Array Elements
  • Initialising Array
  • Getting length of an Array
  • Reusing Array Variables
  • Representation of array in memory

Creating Array

Unlike other languages like C/C++, arrays in Java are implemented as objects. So to create and use an array, you have first to declare the array and then instantiate it using the new operator.

Declaring an Array

Before you can use an array, you must first declare a variable to reference an array and specify the type of array the variable can reference. The syntax for declaring a one-dimensional array is

arrayRefVar = new datatype[size];

Start with the array name with an equals sign afterward. Then come the new keyword and the data type, followed by the square brackets. In those brackets is the size of the array – the number of positions it has. All of this can go on a single  line: 
Here data type is any primitive data type or reference type. It determines the data type of each element in the array. An empty set of square brackets ([]) indicates that an array reference variable arrayRefVar holds a one-dimensional array. The arrayRefVar follows the same rules and conventions as that of identifiers.

 

For example, the declaration declares an array reference variable named num that can store a reference for an integer array. No memory has been yet allocated to hold an array at this time, so the value of the reference variable is null. An alternative notation for declaring the above array is
int num[];
It only differs from the previous one in the placement of the square brackets. This style came from the C language and was adopted in Java to accommodate C programmers.
You can also declare multiple arrays of the same data type in one statement by inserting a comma after each array name. For example.
int [] min,max;
This statement declares min and max array variables that can store reference for integer arrays.

Instantiating an Array

Once you have declared an array reference variable, the next step is to create an array object and assign the reference of the newly created array to the existing array reference variable, using the following syntax,
arrayRefVar = new datatype[size];
Where arrayRefVar is the name of an existing array reference variable that stores the reference of the newly created array. The new keyword allocates memory for the array and size is an expression that evaluates to a positive integer and specifies the number of elements in the array. For example, the statement
num = new int[5];

creates an array of 5 elements of int type and assigns its reference to the array reference variable num.
You can combine the declaration of array variable with instantiation in a single line using the statement,
int[] num = new int[5];
This statement declares an array reference variable num, creates an array of 5 elements of int type and assign its reference to the array reference variable num.
When an array is created like this, its elements are automatically initialised to their default values. The default values are 0 in case of an array of numeric elements, false for boolean arrays, ‘\u0000′(space) for char arrays and null for an array of class type.
Now let us consider some more examples.
double[] dailyTemp = new double[365];
dailyTemp is an array variable that stores the reference to the array containing 365 double type values.
float[] salaries = new float[100];
salaries is an array variable that stores the reference to the array containing 100 float type values.
Student[] s = new Student[20];
s is an array variable that stores reference to the array of 20 Student objects.

Accessing Array Elements

Once the array is created, you can access an array element by using the name of the array followed by an index enclosed between a pair of square brackets. The index or subscript of an array indicates the position of an element in the array. The index of the first element in the array is always 0 (zero), the second element has an index I and so on. The index of the last element is always one less than the number of elements in the array. The syntax for accessing an array element is
arrayRefVar[index];
Here, the index is an integer literal or an expression that evaluates to an int.
In our example, the first element of the array is num [0], the second element is num [1], and the last element is num [4].
NOTE: An index must be an int value or a value of a type that can be promoted to int such as byte, short or char. You are using a value of type long as an array index result in compile time error. One should make sure that array indexes must be between 0 and the number of elements minus 1. Attempting to access an element of an array using an index less than 0 or higher than the index value for the last element in the array will compile without errors but will generate an ArraylndexOutOfBoundsException at run time.
Similarly, to assign a value to an element of a one-dimensional array, use the following syntax
arrayRefVar[index] = value;
For example, to assign a value 15 to an element at index 2, you need to write
num[2] = 15;
Now let us consider a program that demonstrates how to assign values to array elements and then access it.

publicclass ArrayAccessDemo {
   publicstaticvoid main(String[] args){
        int[] num =newint[5];
        num[0]=5;
        num[1]=15;
        num[2]=25;
        num[3]=30;
        num[4]=50;
        System.out.println(“Array Element num[0] = “+ num[0]);
        System.out.println(“Array Element num[1] = “+ num[1]);
        System.out.println(“Array Element num[2] = “+ num[2]);
        System.out.println(“Array Element num[3] = “+ num[3]);
        System.out.println(“Array Element num[4] = “+ num[4]);
     }
}
Output :
Array Element num [0] 5
Array Element num [1] 15
Array Element num [2] 25
Array Element num [3] 30
Array Element num [4] 50
 Now let us consider another program that input the elements of an array and prints its contents.
//input and access array elements
import java.util.Scanner;//program uses Scanner class
publicclass ArrayDemo {
   publicstaticvoid main(String[] args){
       int[] numArray =newint[5];
       int i;
       //Create Scanner object to obtain input from keyboard
       Scanner input =newScanner(System.in);
       System.out.println(“Enter the array elements —->”);
       for(i =0; i<5; i++)
            numarray[i]= input.nextInt();//Read number
       for(i =0; i<numArray.length; i++)
           System.out.println(“Array element[“+i +“] = “+numArray[i]);
    }
}

Explanation: This program inputs an array and prints its contents.
The statement,
int[] numArray = new int[5];
creates a numArray array variable that references an int-array containing 5 elements. We create a Scanner object to obtain an input from the keyboard. Finally, when all the input has been made it is printed.

Initialising Array

When an array is created, each element of the array is set to default initial value according to its type. However, it is also possible to provide value other than the default values to each element of the array.
This is made possible using array initialisation. Arrays can be initialised by providing values using a comma-separated list within curly braces following their declaration. The syntax for array initialization is
datatype[] arrayName = {value1, value2,…….. };
For example : The statement
int[] num = {5,15,25,30,50};
creates a five element array with index values 0,1,2,3,4. The element num [0] is initialized to 5, num [1] is initialized to 15 and so on.
Note that we do not use the new keyword and do not specify the size of the array also. This is because when the compiler encounters such a statement, it counts the number of elements in the list to determine the size of the array and performs the task performed by the new operator. The initialising array is useful if you know the exact number and values of elements in an array at compile time.
The above initialisation statement is equivalent to

int[] num = new int[5];
num [0] = 5 ;
num [1] = 15;
num [2] = 25;
num [3] = 30;
num [4] = 40;
Similarly, you can initialize an array by providing objects in the list. For example
Rectangle[] rect = {new Rectangle(2,3),new Rectangle()};
It will create rect array of Rectangle objects containing 2 elements.
There is a variation of array initialization in which we use the new keyword explicitly but omit the array length as it is determined from the initializer list. For example:
int[] num = new int[]{5,15,25,30,50};
This form of initialization is useful if you need to declare an array in one location but populate it in another while still taking the advantage of array initialization. For example :
displayData(new String[]{“apple”,”orange”,”litchi”});
An unnamed array created in such a way is called anonymous arrays.
Now let us consider the following program that illustrates the use of initialization.

//Different ways of initializing Constructors
publicclass ArrayInitDemo {
  publicstaticvoid main(String[] args){//one way of initializing 1D array
  int[] num =newint[]{5,15,25,30,50};
  for(int i =0; i <num.length; i++)
     System.out.println(“num[“+i+“]=”+num[i]);//second way of initializing 1D array
            display(newString[]{“apple”,“orange”,“litchi”});
   }
     staticvoid display(String[] str){
      for(int i =0; i<str.length;i++)
            System.out.println(“str[“+i+“] =”+str[i]);
     }
}
Output : num[0] = 5
num[l] = 15
num[2] = 25
num[3] = 30
num[4] = 50
str[0] = apple
str[l] = orange
str[2] = litchi

Getting length of an Array

After you create an array, you can access its length i.e. number of elements it holds. You can refer to the length of an array using its length field (which is implicitly public and final).A length field is associated with each array that has been instantiated.

Because length field is a public member so it can be directly accessed using the array name and a dot operator. Its syntax is
arrayRefVar.length
The length data field can be accessed using the dot operator. For example: To access the number of elements in an array named num, use the following syntax,
num.length
You can use the length field of an array to control a numerical for loop that iterates over the elements of an array.
for(int i=0; i<num.length; i++)
System.out.println(“Element num[” + i + “] = ” + num[i]);
Note: An array with length zero is said to be an empty array.
Now let us consider the following programs to explain it.

//Calculate average of 5 numbers
class Average {
   public static void main(String[] args) {
        int[] num = {10,20,30,40,50};
        int sum = 0;
        for(int i = 0; i<num.length; i++){
             sum += num[i];
        }
              double avg =(double)sum/num.length;
               System.out.println(“average = “+avg);
   }
}
Output: average = 30.0
Explanation: The above program calculates the average of 5 numbers. The array containing 5 numbers can be referenced using the num_array variable. Here, we use num.length to get the length of the array referenced by num.
To calculate the average, we first add all the numbers in the array and then divide by the total numbers of elements. The result is then displayed.

Reusing Array Variables

Just like simple variables can store different values at different times, an array variable can also be used to store a reference to different arrays at different times. Suppose you have created and initialized array variable num using the following statement,
int[] num = {5,15,25,30,50};
Suppose later on you want to use the array variable num to refer to another array containing 6 elements of int type then you can do this by simply writing the statement,
num = new int[]{10,20,30,40,50,60};
On execution of this statement, the previous array of 5 int-type elements that is referenced by num is discarded and array variable num now references a new array of 6 values of type int.

 

//program showing reuse of array variable
public class ReuseArray {
   public static void main(String[] args) {
    int[] num = {5,15,25,30,50};
    System.out.println(“Elements in orignal array —>”);
    for(int i = 0;i<num.length; i++)
         System.out.print(num[i]+” “);
         System.out.println(“\nElements in New array –>”);
               num = new int[] {10,20,30,40,50,60};
               for (int i = 0;i<num.length;i++)
                     System.out.print(num[i]+” “);
    }
}
Output : Elements in original array :
5 15 25 30 50
Elements in New array :
10 20 30 40 50 60

Representation of array in memory

1. In java when the array is declared it captures a chunk of memory from the stack.
2. The array is constructed at the run time. At the construction time by specifying the size of the array through new operator garbage collector allocates consecutive memory location from the heap.
3. In java, the compiler implicitly calls the new operator to allocates memory from the heap for the creation of an array without using the new operator.
The Various types of Array those are provided by java as Follows:
1) Single Dimensional Array: These are Mostly used when we want to declare a number of Elements Single Dimensional arrays are used for Using Many elements, and they are Declared with Single Bracket Like int a [] etc. the Bracket will specify the size of array Elements Means how many array elements are declared and used For Accessing or using a variable we have to Specify the Index Value in the SubScript or Bracket of Array Variable.
The [] is used for dimensional or the sub-script of the array that is generally used for declaring the elements of the array For Accessing the Element from the array we can use the Subscript of the Array like this
a[3] = 100
So there is only the single bracket then it  is called as Single Dimensional Array
The Syntax For Declaring Array Elements in java is as follows-
int a[] = new int[5]
Note the new Keyword this is a Special Operator Which is used for Creating new Memory which is Continuous and The new Keyword is Also Creating For Memory For Number of elements That is Specified in Single bracket.

2) Two Dimensional Array: The Two Dimensional array Elements are used when we Wants to Perform the Operation in Matrix Forms the Two Dimensional arrays are used For Creating Matrix and  Displaying array elements in the Form of Rows and Columns The Total Elements of Arrays Will be Calculated by Multiplying the  Elements of Rows and Columns Like int a[3][3] i.e. 9 Elements will be used by Array These are Called as Two Dimensional Because they use two Brackets.
Like this int a[3][3]
So This is the Example of the Two Dimensional Array  In this first 3 represents the total number of Rows and the Second Elements Represents the Total number of Columns  The Total Number of elements are judge by Multiplying the Numbers of Rows * Number of Columns in The Array in the above array the Total Number of elements are 9
The Two Dimensional arrays are Declared as Follows:
int a[][] = new int[3][3].

You’ll also like:

  1. Write A C++ Program To Declare Class Instance (Create Object).
  2. What are the steps to initialize an Array
  3. How can we declare an Array
  4. Write A C++ Program To Create An Array Of Objects.
  5. Multidimensional Array in Java Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW