3 min read•Last Updated on June 18, 2024
Avanish Gupta
Avanish Gupta
Arrays We can use arrays to store data and algorithms can be used to access and traverse through this data.
In this unit, we will start learning about data structures, which are structures that store multiple pieces of data. You will learn about three of them in this course: 1-D Arrays in this unit, ArrayLists in Unit 7, and 2-D Arrays in Unit 8. Arrays store one type of data, whether that be a primitive data type or a reference data type, and they are of fixed size. When used for loops, we can do many things with arrays and build algorithms with them, as well.
In this unit, you will learn three things that are important for larger programs: how to create an array, how to traverse(going through all the elements) an array, and how to manipulate the elements in an array. One of the common mistakes that you may make at first is an ArrayIndexOutOfBoundsException, which occurs when you try to access an element where none exists, but with some practice, you will be flawless with arrays!
Arrays are used to store one type of data, whether it is a primitive or reference data type. Arrays themselves are reference types. They are best thought of as a list of items with a fixed size, as arrays have a set size that cannot be changed (don’t confuse this with ArrayLists which can also be thought of as a list). Arrays are denoted by braces ({}), with items separated by commas such as the following:
{true, true, false, true}
Before we can use arrays, we need to have an import statement, which is
import java.util.Arrays;
There are two ways to make arrays: using a constructor and using a pre-initialized array.
Constructor
As with other reference types, we can initialize arrays using a constructor. However, the constructor is slightly different from the constructors from Unit 5:
dataType[] arrayName = new dataType[numberOfItems];
The items in the array are initialized differently depending on the data type. Integers are initialized to 0, doubles are initialized to 0.0, booleans are initialized to false, and all reference types are initialized to null. We will talk about filling constructed lists in the next topic when we discuss traversing arrays.
Pre-initialized Arrays
We can also set an array to a pre-initialized array, similar to how we initialize strings. Here, we will initialize an array of 10 integers as follows:
int[] arrayOne = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
We access elements in arrays using bracket notation as follows: arrayName[index]. The most important thing to know is that Java is a zero-indexed language, so the first item has index 0, and not 1.
Before we talk about the index of the last item, we need to discuss how to find the array length. The array length is actually an instance variable specific to that particular array denoted as arrayName.length (not to be confused with length() for Strings). Note that this is not a method, so there are no parentheses. Thus, the last item in the array can be accessed by using arrayName.length - 1. Do not confuse this with the constructor in which we use arrayName.lengthin brackets. If we use an index outside the allowed range, we will get an ArrayIndexOutOfBoundsException.
Here is a question: how do we access the even numbers in arrayOne from above?
2 = arrayOne[1]
4 = arrayOne[3]
6 = arrayOne[5]
8 = arrayOne[7]
10 = arrayOne[9]
2-D Arrays (two-dimensional arrays) are rectangular grids or matrices consisting of rows and columns. They allow for storing and accessing elements using two indices - one for row number and another for column number.
Term 1 of 13
2-D Arrays (two-dimensional arrays) are rectangular grids or matrices consisting of rows and columns. They allow for storing and accessing elements using two indices - one for row number and another for column number.
Term 1 of 13
2-D Arrays (two-dimensional arrays) are rectangular grids or matrices consisting of rows and columns. They allow for storing and accessing elements using two indices - one for row number and another for column number.
Term 1 of 13
Arrays are a collection of elements of the same data type, stored in contiguous memory locations. They have a fixed size and can be accessed using an index.
Index: It is the position or location of an element within an array.
Element: An individual item stored in an array.
Length/Size: The total number of elements present in an array.
ArrayLists are dynamic arrays that can grow and shrink dynamically as needed. They provide resizable arrays with additional methods for easy manipulation and management.
Array: An array is a fixed-size data structure that stores a collection of elements of the same type.
List: A list is a collection that maintains the order of its elements and allows duplicates. It can be implemented using various data structures, including ArrayLists.
Resize: Resizing refers to changing the size or capacity of a data structure dynamically, either by expanding or shrinking it as needed.
2-D Arrays (two-dimensional arrays) are rectangular grids or matrices consisting of rows and columns. They allow for storing and accessing elements using two indices - one for row number and another for column number.
Multidimensional Arrays: Multidimensional arrays extend beyond two dimensions (rows and columns). For example, a three-dimensional array adds depth as another dimension along with rows and columns.
Jagged Arrays: Jagged arrays are arrays where each row may have different lengths. This allows for more flexibility when dealing with irregularly shaped data structures compared to regular rectangular 2-D arrays.
Array Indexing: Array indexing refers to accessing or modifying elements in an array using their position or indices. In the case of 2-D arrays, you need to specify both the row and column index to access a particular element.
Primitive data types are basic data types provided by programming languages, such as integers, floating-point numbers, booleans, and characters. They represent simple values and have predefined characteristics.
int: A primitive data type representing whole numbers without decimal points.
boolean: A primitive data type representing true or false values.
char: A primitive data type representing single characters like letters or symbols.
A reference data type is a data type that refers to an object in memory rather than directly storing the value. It stores the memory address where the object is located.
intValue(): This method is used to convert a numeric value stored in an object of a reference data type into an integer value.
doubleValue(): This method is used to convert a numeric value stored in an object of a reference data type into a double value.
toString(): This method returns a string representation of an object, allowing you to easily display or manipulate its contents.
Fixed size refers to a data structure or container whose size cannot be changed once it is created. Once initialized with a specific capacity or length, no additional elements can be added or removed from it.
Array: A fixed-size data structure in many programming languages that stores elements of the same type in contiguous memory locations.
Stack: A data structure that follows the Last-In-First-Out (LIFO) principle, where elements can only be added or removed from one end called the top.
Queue: A data structure that follows the First-In-First-Out (FIFO) principle, where elements can only be added at one end called the rear and removed from the other end called the front.
For loops are control structures used for repetitive execution of code blocks. They consist of an initialization statement, condition statement, increment/decrement statement, and loop body. The loop continues until the condition becomes false.
While Loop: A while loop is another type of control structure that repeatedly executes a block of code as long as a given condition is true.
Nested Loop: A nested loop is a loop inside another loop. It allows for more complex iterations and can be used to traverse multi-dimensional data structures.
Break Statement: The break statement is used within loops to terminate their execution prematurely based on certain conditions.
ArrayIndexOutOfBoundsException is an exception that occurs when trying to access an invalid index position in an array. It is thrown to indicate that the index used to access an array is either negative or greater than or equal to the size of the array.
Exception handling: The process of dealing with and responding to exceptional situations or errors that occur during program execution.
Bounds checking: The practice of verifying whether an index value falls within the valid range of indices before accessing elements in an array.
Runtime error: An error that occurs during program execution rather than during compilation.
Traversing arrays refers to the process of accessing and examining each element in an array. It allows you to perform operations on every element or search for specific values within the array.
Array Algorithms: These are predefined procedures or methods that operate on arrays to solve specific problems efficiently.
Indexing: This term refers to accessing individual elements in an array using their position number.
Linear Search: A searching algorithm that checks each element in an array sequentially until it finds the desired value or reaches the end of the array.
A constructor is a special method within a class that is used to initialize objects of that class. It is called automatically when an object is created and helps set initial values for its attributes.
Class: A class is a blueprint or template for creating objects in object-oriented programming. Constructors belong to classes and define how objects of that class should be initialized.
Instance variables: Instance variables are attributes or properties associated with each instance (object) of a class. Constructors often assign initial values to these instance variables.
Overloading: Constructor overloading allows multiple constructors within the same class, but with different parameter lists. This provides flexibility in creating objects with varying initialization options.
The syntax arrayName[index] is used in programming languages to access a specific element within an array. "arrayName" represents the name of the array, and "index" refers to the position of the desired element.
Array: An array is a data structure that stores a fixed-size sequence of elements of the same type. It allows for efficient storage and retrieval of multiple values using indexes.
Element: An element refers to an individual value stored within an array or collection. Each element has its own unique index that determines its position within the data structure.
Index Out-of-Bounds Error: An index out-of-bounds error occurs when you try to access or modify an element using an invalid index (outside the valid range). It can result in runtime errors or unexpected behavior.
In computer programming, zero-indexed language refers to systems where counting starts from 0 instead of 1 when accessing elements in an ordered collection (e.g., arrays).
Array: An array is an ordered collection of elements stored in contiguous memory locations. Each element can be accessed using its index.
Index out of bounds: This term refers to trying to access an element outside the valid range of indices for a given data structure, resulting in an error.
Loop: A loop is a programming construct that allows executing a set of instructions repeatedly until a specific condition is met. It often involves iterating over elements in an ordered collection using their indices.
The property "length" is used to determine the number of elements in an array.
index: A value that represents the position of an element in an array.
element: Each individual item stored in an array.
loop: A programming construct that allows you to repeat a set of instructions multiple times.