What is an Array in Java?
An array is a data structure used to store multiple values of the same type in contiguous memory locations.
Java arrays:
- Are fixed in size
- Store elements of the same data type
- Are objects (even if they store primitive data)
Syntax of an Array
// When values are known at the time of declaration
datatype[] arrayName = { value1, value2, value3 };
// When size is known but values are not yet assigned
datatype[] arrayName = new datatype[size];
Examples:
String[] cars = { "Volvo", "BMW", "Ford" }; // Known values
int[] num = new int[5]; // If we don't know the values
Accessing & Changing Elements
You can access an array element using its index (starting from 0):
System.out.println(cars[0]); // Output: Volvo
You can change an element like this:
cars[0] = "Opel";
Finding Array Length
Use .length to get the number of elements in an array:
System.out.println(cars.length); // Output: 3
Why Use Arrays?
- To store multiple values in a single variable
- For efficient data management
- Stored in contiguous memory locations
- Useful when working with fixed-size collections
Common Errors
int[] num = new int[5];
num[5] = 10; // ArrayIndexOutOfBoundsException
This error occurs because array indices start from 0, so the valid range is 0 to length - 1.
Arrays are Objects in Java
In Java, every array is an object. That’s why we can also create arrays using the new keyword:
String[] cars = new String[3];
When you print an array directly, you’ll see something like:
System.out.println(cars);
// Output: [Ljava.lang.String;@16bd3586
Let’s break this down:
-
[Ljava.lang.String;
➝ Means it’s an array of String -
@
➝ Separator -
16bd3586
➝ Hexadecimal hashcode (reference string, varies each time)
Array of Objects
Arrays can also store objects:
Home[] obj = new Home[2];
This creates an array of Home
objects.
Can Arrays Store Negative Values?
Yes, if the data type supports it, you can store negative numbers:
int[] nums = { -10, -20, -30 };
Supported types that allow negative values:
- int
- float
- double
- byte
- short
- long
Top comments (0)