- Understand how to declare, initialize, and manipulate arrays
- Learn string operations and methods in Java
- Master common array and string manipulation techniques
Arrays and Strings in Java
Introduction
Arrays and strings are fundamental data structures in Java. Arrays allow you to store multiple values of the same type, while strings represent sequences of characters. Understanding how to work with arrays and strings is crucial for handling collections of data and text manipulation in Java programs.
Arrays in Java
An array is a fixed-size, homogeneous data structure that stores elements of the same type in contiguous memory locations.
Declaring Arrays
// Method 1: Declare and allocate separately
int[] numbers;
numbers = new int[5];
// Method 2: Declare and allocate in one line
int[] scores = new int[10];
// Method 3: Declare, allocate, and initialize
int[] values = {1, 2, 3, 4, 5};
Accessing Array Elements
Array elements are accessed using zero-based indexing.
int[] arr = {10, 20, 30, 40, 50};
System.out.println(arr[0]); // Output: 10
System.out.println(arr[2]); // Output: 30
// Modifying elements
arr[1] = 25;
System.out.println(arr[1]); // Output: 25
Array Length
Use the length property to get the size of an array.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Array length: " + numbers.length); // Output: 5
Iterating Through Arrays
Using for Loop
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
Using Enhanced for Loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
Multidimensional Arrays
Java supports arrays of arrays (multidimensional arrays).
// 2D array declaration
int[][] matrix = new int[3][4];
// 2D array initialization
int[][] matrix2 = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Accessing 2D array elements
System.out.println(matrix2[0][0]); // Output: 1
System.out.println(matrix2[1][2]); // Output: 7
Strings in Java
Strings in Java are objects that represent sequences of characters. The String class is immutable, meaning once created, a String object cannot be changed.
Creating Strings
// String literals
String str1 = "Hello, World!";
// Using new keyword
String str2 = new String("Hello, World!");
// Empty string
String empty = "";
String Methods
Length
String text = "Hello";
System.out.println(text.length()); // Output: 5
Character Access
String text = "Hello";
char firstChar = text.charAt(0); // 'H'
char lastChar = text.charAt(text.length() - 1); // 'o'
Substring
String text = "Hello, World!";
String sub1 = text.substring(7); // "World!"
String sub2 = text.substring(0, 5); // "Hello"
String Comparison
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
System.out.println(str1 == str2); // true (same reference)
System.out.println(str1 == str3); // false (different references)
System.out.println(str1.equals(str3)); // true (same content)
Case Conversion
String text = "Hello, World!";
String upper = text.toUpperCase(); // "HELLO, WORLD!"
String lower = text.toLowerCase(); // "hello, world!"
String Concatenation
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // "John Doe"
// Using concat() method
String greeting = "Hello".concat(", World!"); // "Hello, World!"
String Searching
String text = "Hello, World!";
System.out.println(text.contains("World")); // true
System.out.println(text.indexOf("World")); // 7
System.out.println(text.startsWith("Hello")); // true
System.out.println(text.endsWith("!")); // true
String Replacement
String text = "Hello, World!";
String replaced = text.replace("World", "Java"); // "Hello, Java!"
String replacedAll = text.replaceAll("l", "L"); // "HeLLo, WorLd!"
String Immutability
Since strings are immutable, methods that appear to modify strings actually return new String objects.
String original = "Hello";
String modified = original.toUpperCase();
System.out.println(original); // "Hello" (unchanged)
System.out.println(modified); // "HELLO" (new string)
StringBuilder and StringBuffer
For mutable strings or frequent string modifications, use StringBuilder (not thread-safe) or StringBuffer (thread-safe).
StringBuilder sb = new StringBuilder("Hello");
sb.append(", World!");
sb.insert(5, " Beautiful");
String result = sb.toString(); // "Hello Beautiful, World!"
Common Array and String Operations
Array Copying
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[source.length];
System.arraycopy(source, 0, destination, 0, source.length);
Array Sorting
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers); // numbers is now {1, 2, 5, 8, 9}
String Splitting
String csv = "apple,banana,orange";
String[] fruits = csv.split(","); // ["apple", "banana", "orange"]
Joining Strings
String[] words = {"Hello", "World", "!"};
String sentence = String.join(" ", words); // "Hello World !"
Best Practices
- Always check array bounds to avoid
ArrayIndexOutOfBoundsException. - Use enhanced for loops when you don't need index-based access.
- Prefer
equals()method for string comparison over==operator. - Use
StringBuilderfor concatenating strings in loops. - Be aware of string immutability when performing multiple operations.
- Use
Arraysutility class for common array operations.
Summary
Arrays and strings are essential components of Java programming. Arrays provide a way to store and manipulate collections of data efficiently, while strings offer powerful methods for text processing. By mastering these fundamental data structures, you'll be able to handle more complex data manipulation tasks in your Java applications.
