A data structure is a storage that is used to store and organize data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently. Most essential and responsible for organizing, processing, accessing, and storing data efficiently.
Data Structures are divided based on how they are arranged in the memory
Data elements are arranged sequentially or linearly, where each element is attached to its previous and next adjacent elements. Examples: Arrays, Queue, Stack
Data structures where data elements are not placed sequentially or linearly are called non-linear data structures. Examples: Trees, Graphs
An array is a collection of homogenous data type. A collection of items stored at contiguous memory locations. Each item in an array is indexed starting with 0.
/* Static Arrays are arrays that are declared before runtime
and are assigned values while writing the code.
*/
// The syntax of declaring a static array is:
<data type><variable name>[]
= {<data1>, <data2>,…..<dataN> };
// Example:
int arr[] = { 2, 5, 6, 9, 7, 4, 3 };
Array is accessed by referring to index number
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
for (type variable : arrayname) {
...
}
Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Here’s a video overview of arrays
Now try it for yourself by completing Arrays Exercise