Ticker

6/recent/ticker-posts

Java Arrays Tutorial


Java Arrays Tutorial

Introduction

In Java, an array is a data structure that allows you to store a fixed-size sequential collection of elements of the same type. Arrays are useful for storing and manipulating multiple values under a single variable name. This tutorial will cover how to declare, create, and initialize arrays in Java with examples.

1. Declaring Arrays

To declare an array in Java, you need to specify the data type of the elements followed by the array name and square brackets []. The syntax is as follows:

java
dataType[] arrayName;

Example:

java
int[] numbers;
String[] names;

2. Creating Arrays

After declaring an array, you need to allocate memory for it using the new keyword along with the array's data type and the desired size (number of elements) enclosed in square brackets []. The created array will be initialized with default values (e.g., 0 for numeric types, null for reference types).

java
dataType[] arrayName = new dataType[arraySize];

Example:

java
int[] numbers = new int[5];
String[] names = new String[10];

3. Initializing Arrays

Java allows you to initialize arrays with specific values at the time of declaration or later on. Here are two common ways to initialize arrays:

3.1. Inline Initialization

You can initialize an array with specific values at the time of declaration, known as inline initialization. The number of elements in the array determines the array size automatically.

java
dataType[] arrayName = {value1, value2, value3, ...};

Example:

java
int[] numbers = {10, 20, 30, 40, 50};
String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

3.2. Initializing Elements Individually

You can also initialize array elements individually after creating the array using the index (starting from 0).

java
dataType[] arrayName = new dataType[arraySize];
arrayName[index] = value;

Example:

java
int[] numbers = new int[3];
numbers[0] = 100;
numbers[1] = 200;
numbers[2] = 300;

Conclusion

Arrays are fundamental data structures in Java, allowing you to store and access multiple elements of the same type efficiently. This tutorial covered the basics of declaring, creating, and initializing arrays with examples to get you started with array manipulation in Java.

Post a Comment

0 Comments