Core Java Concepts: Arrays and Strings

Core Java Concepts: Arrays and Strings
1. Arrays in Java
An array is a collection of elements of the same type, stored in contiguous memory locations.
1.1 Declaring and Initializing Arrays
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};
// Access elements
System.out.println(numbers[0]); // Output: 10
System.out.println(numbers[2]); // Output: 30
int[] arr = new int[5]; // Array of size 5
// Assigning values
arr[0] = 5;
arr[1] = 10;
arr[2] = 15;
System.out.println(arr[1]); // Output: 10
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
for (int num : numbers) {
System.out.println(num);
}
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
System.out.println(matrix[0][1]); // Output: 2
System.out.println(matrix[2][2]);
// Output: 9
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // New line
}
String str1 = "Hello"; // String literal
String str2 = new String("World"); // Using new keyword
public class StringExample {
public static void main(String[] args) {
String s = " Hello Java ";
System.out.println("Original: " + s);
System.out.println("Trimmed: " + s.trim());
System.out.println("Uppercase: " + s.toUpperCase());
System.out.println("Substring: " + s.substring(1, 6));
}
}
Original: Hello Java
Trimmed: Hello Java
Uppercase: HELLO JAVA
Substring: ello
4. StringBuilder and StringBuffer
4.1 Why Use StringBuilder or StringBuffer?
Strings are immutable: Modifying a String creates a new object.
StringBuilder and StringBuffer are mutable, meaning they allow modifications without creating new objects.
4.2 Differences Between StringBuilder and StringBuffer
Feature StringBuffer StringBuilder
Thread Safety Yes (synchronized) No (faster but not thread-safe)
Performance Slower (due to thread safety) Faster
4.3 Using StringBuilder
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
sb.insert(5, " Java");
System.out.println(sb); // Output: Hello Java World
sb.replace(6, 10, "C++");
System.out.println(sb); // Output: Hello C++ World
sb.delete(6, 10);
System.out.println(sb); // Output: Hello World
sb.reverse();
System.out.println(sb); // Output: dlroW olleH
}
}
4.4 Using StringBuffer (Thread-Safe Alternative)
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb); // Output: Java Programming
}
}
Date: 2025-03-28 00:00:00.000000