ARRAYS
• Array is a collection of similar type of elements which has contiguous
memory location.
• Java array is an object which contains elements of a similar data
type. Additionally, The elements of an array are stored in a contiguous
memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at
the 0th index, 2nd element is stored on 1st index and so on.
• Unlike C/C++, we can get the length of the array using the length
member. In C/C++, we need to use the sizeof operator.
• In Java, all arrays are dynamically allocated. (discussed below)
• Arrays are stored in contiguous memory [consecutive memory locations].
• Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the data
type.
• The variables in the array are ordered, and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method parameter.
• The size of an array must be specified by int or short value and not long.
• The direct superclass of an array type is Object.
• This storage of arrays helps us randomly access the elements of an array [Support
Random Access].
• The size of the array cannot be altered(once initialized). However, an array
reference can be made to point to another array.
Advantages:
Code Optimization: It makes the code optimized, we can retrieve or
sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages:
Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Creating, initializing, and accessing an Array
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is
type var_name[];
type[] var_name;
Example:
int intArray[];
or int[] intArray;
• An array declaration has two components: the type and the name. type declares the element type of the
array.
• The element type determines the data type of each element that comprises the array. Like an array of
integers, we can also create an array of other primitive data types like char, float, double, etc., or
user-defined data types (objects of a class).
• Thus, the element type for the array determines what type of data the array will hold.
Instantiating an Array in Java
• When an array is declared, only a reference of an array is created. To
create or give memory to the array, you create an array like this: The
general form of new as it applies to one-dimensional arrays appears as
follows:
Var_name = new type size[];
Here, type specifies the type of data being allocated, size determines the
number of elements in the array, and var-name is the name of the array
variable that is linked to the array.
To use new to allocate an array, you must specify the type and
number of elements to allocate.
EXAMPLE
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
Or
int[] intArray = new int[20];
The elements in the array allocated by new will automatically be initialized
to zero (for numeric types), false (for boolean), or null (for reference types).
ARRAY LITERAL
• In a situation where the size of the array and variables of the array are
already known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
• The length of this array determines the length of the created array.
• There is no need to write the new int[] part in the latest versions of
Java
Accessing Java Array Elements using for Loop
• Each element in the array is accessed via its index. The index begins with
0 and ends at (total array size)-1. All the elements of array can be
accessed using Java for Loop.
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + " : "+ arr[i]);
class CSE {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// allocating memory for 5 integers. OUTPUT:
arr = new int[5]; Element at index 0 : 10
Element at index 1 : 20
// initialize the elements of the array
Element at index 2 : 30
arr[0] = 10; Element at index 3 : 40
arr[1] = 20; Element at index 4 : 50
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i+ " : " + arr[i]);
}
}
Array Index Out Of Bounds Exception
What happens if we try to access elements outside the array size?
JVM throws ArrayIndexOutOfBoundsException to indicate that the
array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of an array.
public class CSE {
public static void main(String[] args) OUTPUT:
{ Trying to access element outside the size of array
Exception in thread "main"
int[] arr = new int[4];
[Link]: Index 5
arr[0] = 10; out of bounds for length 4
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
[Link]("Trying to access element outside the size of
array");
[Link](arr[5]);
}
}
Multidimensional Arrays:
• Multidimensional arrays are arrays of arrays with each element of
the array holding the reference of other arrays. These are also known
as Jagged Arrays.
• A multidimensional array is created by appending one set of square
brackets ([]) per dimension.
Syntax :
datatype [][] arrayrefvariable;
or
datatype arrayrefvariable[][];
public class multiDimensional {
public static void main(String args[])
OUTPUT:
{
279
// declaring and initializing 2D array 361
int arr[][] 742
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
Passing Arrays to Methods
public class Test {
// Driver method OUTPUT:
public static void main(String args[])
{
Sum of array values:15
int arr[] = { 3, 1, 2, 5, 4 };
// passing array to method m1
sum(arr);
}
public static void sum(int[] arr)
{
// getting sum of array values
int sum = 0;
for (int i = 0; i < [Link]; i++)
sum += arr[i];
[Link]("sum of array values : " + sum);
}
}