Arrays in Java
Arrays in Java
Arrays in Java
• 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 size of.
• 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.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a
class, depending on the definition of the array. In the case of primitive data types, the actual
values might be stored in contiguous memory locations (JVM does not guarantee this
behavior). In the case of class objects, the actual objects are stored in a heap segment.
Note: This storage of arrays helps us randomly access the elements of an array.
One-Dimensional Arrays
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.
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:
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:
//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: 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).
Obtaining an array is a two-step process. First, you must declare a variable of the desired
array type. Second, you must allocate the memory to hold the array, using new, and assign it
to the array variable. Thus, in Java, all arrays are dynamically allocated.
In a situation where the size of the array and variables of the array are already known, array
literals can be used.
• 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.
class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Syntax:
Example 1:
import java.io.*;
class GFG {
public static void main (String[] args) {
System.out.println("Array Size:"+arr.length);
}
}
Output
Array Size:4
The student Array contains five memory spaces each of the size of student class in which the
address of five Student objects can be stored. The Student objects have to be instantiated
using the constructor of the Student class, and their references should be assigned to the array
elements in the following way.
Example 2:
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");
Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit
Example 3
class Student
{
Output
Dharma
sanvi
Rupa
Ajay
Below code shows what happens if we try to access elements outside the array size:
System.out.println(
"Trying to access element outside the size of array");
System.out.println(arr[5]);
}
}
Output
Output
10
20
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.
Example:
// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column
// Number of Rows
System.out.println("Number of Rows:"+
arr.length);
// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}
Output
Number of Rows:3
Number of Columns:3
Output
2 7 9
3 6 1
7 4 2
// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 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++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output
2 7 9
3 6 1
7 4 2
Like variables, we can also pass arrays to methods. For example, the below program passes
the array to method sum to calculate the sum of the array’s values.
Output
sum of array values : 15
As usual, a method can also return an array. For example, the below program returns an array
from method m1.
class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();
Output
1 2 3
class Test {
public static void main(String args[])
{
int intArray[] = new int[3];
byte byteArray[] = new byte[3];
short shortsArray[] = new short[3];
// array of Strings
String[] strArray = new String[3];
System.out.println(intArray.getClass());
System.out.println(
intArray.getClass().getSuperclass());
System.out.println(byteArray.getClass());
System.out.println(shortsArray.getClass());
System.out.println(strArray.getClass());
}
}
Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;
1. The string “[I” is the run-time type signature for the class object “array with
component type int.”
3. The string “[B” is the run-time type signature for the class object “array with
component type byte.”
4. The string “[S” is the run-time type signature for the class object “array with
component type short.”
5. The string “[L” is the run-time type signature for the class object “array with
component type of a Class.” The Class name is then followed.
Now, as you know that arrays are objects of a class, and a direct superclass of arrays is a class
Object. The members of an array type are all of the following:
• The public final field length contains the number of components of the array. Length
may be positive or zero.
• All the members are inherited from class Object; the only method of Object that is not
inherited is its clone method.
• The public method clone() overrides the clone method in class Object and throws no
checked exceptions.
class Test {
public static void main(String args[])
{
int intArray[] = { 1, 2, 3 };
Output
false
1 2 3
Cloning Multidimensional Array in Java
A clone of a multi-dimensional array (like Object[][]) is a “shallow copy,” however, which is
to say that it creates only a single new array with each element array a reference to an original
element array, but subarrays are shared.
class Test {
public static void main(String args[])
{
int intArray[][] = { { 1, 2, 3 }, { 4, 5 } };
Output
false
true
true