DATA STRUCTURE USING JAVA
ASSIGNMENT-2
Bound Checking:
Bound checking is a safety mechanism
implemented in programming languages to prevent
access to memory locations that are outside the
valid range of an array or data structure. It helps
prevent buffer overflows and other memory-related
errors that could lead to unpredictable behavior,
crashes, or security vulnerabilities.
For example, if you have an array of size N,
attempting to access or modify an element at an
index greater than or equal to N, or less than 0 (for
zero-based indexing), could result in a bound-
checking error. Modern programming languages
often include automatic bound checking as part of
their array or container implementations to
enhance program reliability and security.
Despite the benefits of bound checking, it comes
with a performance cost, as each array access
requires additional checks. Some languages, like C
or C++, offer options to disable bound checking for
performance-critical sections of code when the
programmer is confident about the array indices'
validity.
ArrayList:
An ArrayList is a dynamic array implementation in
Java and some other programming languages.
Unlike traditional arrays in languages like C or C++,
ArrayLists can dynamically resize themselves,
making them more flexible. The ArrayList class is
part of the Java Collections Framework and
provides a resizable array backed by a Java array.
Key features of ArrayList include:
1. Dynamic Sizing: ArrayLists can dynamically resize
themselves as elements are added or removed,
eliminating the need to specify the size in advance.
2. Random Access: Elements in an ArrayList can be
accessed randomly using their index, similar to
regular arrays.
3. Automatic Resizing: When the capacity is
exceeded, an ArrayList automatically increases its
size, usually by doubling it, to accommodate more
elements efficiently.
4. Built-in Methods: ArrayLists come with various
built-in methods for adding, removing, and
accessing elements, making them convenient for
many programming tasks.
5. Generics Support: ArrayLists in Java use generics,
allowing them to store elements of a specific type,
providing type safety.
Example usage in Java:
java
import [Link];
public class Example {
public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList<String> arrayList = new ArrayList<>();
// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
// Accessing elements
[Link]([Link](0)); //
Output:
Apple
// Removing elements
[Link]("Banana");
// Size of the ArrayList
[Link]("Size: " + [Link]()); //
Output: 2
}
}