Strings and Arrays

Comprehensive study notes, diagrams, and exam preparation for Strings and Arrays.

Strings and Arrays in Java

Definition

In Java, an Array is a container object that holds a fixed number of values of a single type, while a String is an object that represents a sequence of character values. Both are fundamental data structures used to store and manipulate collections of data efficiently.


Main Content

1. Arrays

  • Arrays are indexed structures where each element is accessed via a numeric index starting at 0.
  • Once created, the size of an array in Java cannot be changed; it is fixed during initialization.

2. Strings

  • In Java, Strings are immutable, meaning once a String object is created, its value cannot be changed.
  • Strings are part of the java.lang package and are frequently used to handle text data throughout an application.

3. Memory Representation

  • Arrays store primitive types or object references in contiguous memory locations.
  • Strings are stored in a special memory area called the "String Pool" to optimize memory usage.
Array Memory (int[] arr = {10, 20, 30}):
Index: [0]  [1]  [2]
Value: |10| |20| |30|

Working / Process

1. Array Initialization

  • Declare the array type followed by brackets: int[] numbers;
  • Allocate memory using the new keyword: numbers = new int[5];

2. String Creation

  • Literal approach: String name = "Java"; (checks the String Pool first).
  • Object approach: String name = new String("Java"); (forces creation of a new object in the heap).

3. Accessing Elements

  • For Arrays, use the bracket notation: int val = numbers[0];
  • For Strings, use built-in methods like charAt(index) or substring() to access specific data: char c = name.charAt(0);

Advantages / Applications

  • Arrays provide high-performance, fast access to data because they are stored in contiguous memory.
  • Strings facilitate easy text manipulation, searching, and comparison through a vast library of built-in methods.
  • Both are essential building blocks for implementing complex data structures like Lists, Stacks, and Queues.

Summary

Arrays are fixed-size containers for homogeneous data, while Strings are immutable sequences of characters used for text processing. Understanding these two concepts is critical for Java programming as they form the foundation for data storage and management. Important terms to remember: Immutable, Index, Contiguous Memory, String Pool, and Heap.