In java, arrays are treated as objects.
While using arrays, we create objects for arrays, whose class is
non-existent (which we have not done so far.)
Whenever JVM encounters [], it understand that it has to create an
object. Thus, array objects can be created without using the ‘new’ operator.
One of the peculiar characteristics of the array is that, without
using the name of the class, we use ‘new’ operator to create an array object.
In any programming language, we cannot create an object without
mentioning the size of the array.
Once the size is defined , it is fixed .we cannot alter it during
run time.
Ex:
Int arr[] = new int[5];
arr is reference to an array of integer type.
System.out.println(arr[0]);
The above statement prints ‘0’ because uninitialized locations(values)
would be initialized with their default values.
arr[1] = 10; // initialize the location with index 1 to 10.
Length: It is an
non-static variable defined inside array object and the values of that
variables is nothing but the size of the array.
System.out.println(arr.length); // prints the size of the array
arr.
Note : With respect to arrays, length is not a function
. As mentioned above, it is a non-static variable that belong to array object.
Creating
array object without using ‘new’ operator
Class Ademo1
{
Public static
void main (String args[])
{
Int i[] = {10,9,8,7};
Char ch[] =
{‘a’,’b’,’c’,’9’,’4’};
System.out.println(ch[i]); // ch[1] = b
System.out.println(i[1]); // ch[1] = 9
}
}
Note: As soon as JVM encounters {}, it creates an
object with the values present in {} and assigns the address of the object to a
variable.
In the way, we can create array objects of all primitive data
types.
In a similar way, we can define arrays of the objects of classes.