Special Offer take any 4 courses for INR 21999.00*

Courses
0

How do you create an array in Java? Provide an example.

December 26, 2024

In Java, an array is a collection of elements of the same data type stored at contiguous memory locations. Here’s how you can create and initialize an array:
1. Declaration
To declare an array, specify the data type and use square brackets []. For example:
int[] numbers; // Declaration of an integer array
2. Initialization
You can initialize an array during or after declaration:
During Declaration:
int[] numbers = {1, 2, 3, 4, 5}; // Initializes an array with values
After Declaration:
numbers = new int[5]; // Allocates memory for 5 integers
numbers[0] = 10; // Assigns values to array elements
3. Example
Here’s a complete example of declaring, initializing, and accessing an array:
public class ArrayExample {
public static void main(String[] args) {
// Declaration and Initialization
int[] numbers = {10, 20, 30, 40, 50};
// Accessing elements
for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } } } Types of Arrays Single Dimensional Array: Example above. Multidimensional Array: Arrays with multiple rows and columns, e.g., int[][] matrix. Arrays are useful for storing and managing collections of data efficiently.

Leave a Comment

Drop a Query

Whether to upskill or for any other query, please drop us a line and we'll be happy to get back to you.

Drop a Query NEW

Request A Call Back

Please leave us your contact details and our team will call you back.

Request A Call Back

By tapping Submit, you agree to Cambridge infotech Privacy Policy and Terms & Conditions

Enquiry Now

Enquiry popup