DEV Community

Deepikandas
Deepikandas

Posted on

#25 Known is a drop! Arrays in Java

Arrays:
A collection of elements of the same type stored under a single name, accessible by numeric indices, with a fixed size.
Key Points About Arrays
Fixed size:
Once created, the number of elements cannot change.

Example: int[] numbers = new int[5]; → can only hold 5 integers.
Same type elements:
All elements must be of the same data type (e.g., int, String, boolean).
Indexed access:
Elements are accessed using indices, starting from 0.
Example: numbers[0] → first element, numbers[4] → fifth element.
Declaration syntax:
type[] arrayName; // preferred style
type arrayName[]; // also valid
Initialization examples:
// Using 'new' keyword
int[] nums = new int[5];

// Using array literal
int[] nums2 = {1, 2, 3, 4, 5};
Memory layout:
Arrays are contiguous in memory, which allows fast index-based access.
Multidimensional arrays:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Access element: matrix[0][2] → 3
Looping through Array :


    for(int i = 0; i < arr.length; i++)
    {
        System.out.println(arr[i]);
    }
Enter fullscreen mode Exit fullscreen mode

Is Array an Object?
When you create an array, Java allocates it on the heap.
The array variable actually holds a reference (like a pointer) to that object.
Because it’s an object, it inherits methods from java.lang.Object, such as:
hashCode()
toString()
clone()
getClass()
Behind the scenes:
int[] numbers = {1, 2, 3};
This is called an array initializer (or array literal).
Even though you didn’t explicitly write new int[3], Java implicitly creates an array object on the heap behind the scenes.
So numbers still holds a reference to an array object.

//getClass(); instanceof
package arrays;

public class Arrays {
    public static void main(String[] value) {
        int arr[]= {23,89,90,78};
        System.out.println(arr.getClass());
        System.out.println(arr instanceof Object);
    }

}
Output:
class [I
true
Enter fullscreen mode Exit fullscreen mode

What is a runtime class?

  • The runtime class is the actual class of the object in memory at runtime.
  • It may be a standard Java class, your own user-defined class, or even an array type. 2️⃣ Examples of runtime classes that are NOT predefined User-defined class
class Student { }

Student s = new Student();
System.out.println(s.getClass()); // class Student
Student is not a predefined Java classits created by the programmer.

Enter fullscreen mode Exit fullscreen mode

Runtime class is Student.
Array objects

int[] numbers = {1, 2, 3};
System.out.println(numbers.getClass()); // class [I
[I  array of integers
Enter fullscreen mode Exit fullscreen mode

There is no class literally named [I in your code.
Arrays are runtime objects created by the JVM, automatically

Top comments (0)