Arrays in Java
Arrays in Java
type var-name[];
OR
type[] var-name;
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 array of int type, we can also create an array
of other primitive data types like char, float, double..etc or user defined data
type(objects of a class).Thus, the element type for the array determines what type of
data the array will hold.
Example:
// both are valid declarations
int intArray[];
or int[] intArray;
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
Although the above first declaration establishes the fact that intArray is an array
variable, no array actually exists. It simply tells to the compiler that this(intArray)
variable will hold an array of the integer type. To link intArray with an actual, physical
array of integers, you must allocate one using new and assign it to intArray.
Instantiating an Array in Java
When an array is declared, only a reference of array is created. To actually create or
give memory to 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 specifies the number of
elements in the array, and var-name is the name of array variable that is linked to the
array. That is, 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]; // combining both statements in one
Note :
1. 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).Refer Default array values in Java
2. 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 that
will hold the array, using new, and assign it to the array variable. Thus, in Java
all arrays are dynamically allocated.
Array Literal
In a situation, where the size of the array and variables of 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.
Implementation:
class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;
// allocating memory for 5 integers.
arr = new int[5];
//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the
following way.
Student[] arr = new Student[7]; //student is a user-defined class
The studentArray contains seven memory spaces each of size of student class in
which the address of seven 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.
Student[] arr = new Student[5];
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");
class GFG
{
public static void main (String[] args)
{
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;
Output:
10
20
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding
the reference of other array. These are also known as Jagged Arrays. A
multidimensional array is created by appending one set of square brackets ([]) per
dimension. Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
class multiDimensional
{
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
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = m1();
Every array has an associated Class object, shared with all other arrays with the
same component type.
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;
Explanantion :
1. The string “[I” is the run-time type signature for the class object “array with
component type int“.
2. The only direct superclass of any array type is java.lang.Object.
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.
Array Members
Now as you know that arrays are object of a class and direct superclass of arrays is
class Object.The members of an array type are all of the following:
The public final field length, which contains the number of components of the
array. length may be positive or zero.
All the members inherited from class Object; the only method of Object that is
not inherited is its clone method.
The public method clone(), which overrides clone method in class Object and
throws no checked exceptions.
Cloning of arrays
When you clone a single dimensional array, such as Object[], a “deep copy” is
performed with the new array containing copies of the original array’s elements
as opposed to references.
// Java program to demonstrate
// cloning of one-dimensional arrays
class Test
{
public static void main(String args[])
{
int intArray[] = {1,2,3};
1 2 3
class Test
{
public static void main(String args[])
{
int intArray[][] = {{1,2,3},{4,5}};
}
}
Output;
false
true
true