What is array in java?
- In Java, an array is a fundamental data structure that serves as a container object holding a fixed number of values of a single type. These values are stored in contiguous memory locations and are accessed using a zero-based index.
Why array using in java?
- Arrays are used in Java for several key reasons, primarily to efficiently manage and store collections of data of the same type:
Key features of Arrays:
Contiguous Memory Allocation (for Primitives):
- Java array elements are stored in continuous memory locations, which means that the elements are placed next to each other in memory.
Zero-based Indexing:
- The first element of the array is at index 0.
Fixed Length:
- Once an array is created, its size is fixed and cannot be changed.
Can Store Primitives & Objects:
- Java arrays can hold both primitive types (like int, char, boolean, etc.) and objects (like String, Integer, etc.)
Basics of Arrays in Java
- There are some basic operations we can start with as mentioned below:
1. Array Declaration
- To declare an array in Java, use the following syntax:
type[] arrayName;
type: The data type of the array elements (e.g., int, String).
Arrayname: The name of the array.
Note: The array is not yet initialized.
2. Create an Array
- To create an array, you need to allocate memory for it using the new keyword:
// Creating an array of 5 integers
int[] numbers = new int[5];
This statement initializes the numbers array to hold 5 integers. The default value for each element is 0.
3. Access an Element of an Array
- We can access array elements using their index, which starts from 0:
// Setting the first element of the array
numbers[0] = 10;
// Accessing the first element
int firstElement = numbers[0];
The first line sets the value of the first element to 10. The second line retrieves the value of the first element.
4. Change an Array Element
* To change an element, assign a new value to a specific index:
// Changing the first element to 20
numbers[0] = 20;
5. Array Length
- We can get the length of an array using the length property:
// Getting the length of the array
int length = numbers.length;
sample program for array string
public class Example {
public static void main(String[] args) {
String[] myArray = {"foo", "bar", "baz"};
// retrieval
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
}
}
REFFERED LINKS
1.https://www.geeksforgeeks.org/java/arrays-in-java/
2.https://opensource.com/article/22/11/arrays-java
Top comments (0)