Loading...

Go Back

Next page
Go Back Course Outline

Java Full Course


Arrays and Strings in Java

Arrays are used to store multiple values in a single variable. All elements must be of the same type.

One-Dimensional Arrays:

Creating and Accessing Arrays
public class ArrayExample {
    public static void main(String[] args) {
        // Declare and initialize an array
        int[] numbers = {10, 20, 30, 40, 50};
        
        // Access elements
        System.out.println("First element: " + numbers[0]);
        System.out.println("Third element: " + numbers[2]);
        
        // Modify an element
        numbers[1] = 25;
        System.out.println("Modified second element: " + numbers[1]);
        
        // Array length
        System.out.println("Array length: " + numbers.length);
    }
}
Output:
First element: 10
Third element: 30
Modified second element: 25
Array length: 5
[0]
10
[1]
25
[2]
30
[3]
40
[4]
50

Multi-Dimensional Arrays:

2D Array Example
public class MatrixExample {
    public static void main(String[] args) {
        // Create a 3x3 matrix
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        
        // Access elements
        System.out.println("Center element: " + matrix[1][1]);
        
        // Print the entire matrix
        System.out.println("Matrix:");
        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();
        }
    }
}
Output:
Center element: 5
Matrix:
1 2 3
4 5 6
7 8 9
1
2
3
4
5
6
7
8
9

Enhanced for Loop:

Iterating with Enhanced for
public class EnhancedForLoop {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
        
        System.out.println("Fruits:");
        for (String fruit : fruits) {
            System.out.println("- " + fruit);
        }
        
        int sum = 0;
        int[] numbers = {5, 10, 15, 20};
        for (int num : numbers) {
            sum += num;
        }
        System.out.println("Sum: " + sum);
    }
}
Output:
Fruits:
- Apple
- Banana
- Cherry
- Date
Sum: 50
Array Operations

Java provides various operations for working with arrays, including sorting and searching.

Sorting Arrays:

Sorting with Arrays.sort()
import java.util.Arrays;

public class ArraySorting {
    public static void main(String[] args) {
        int[] numbers = {42, 13, 7, 25, 30, 18};
        
        System.out.println("Original array: " + Arrays.toString(numbers));
        
        // Sort the array
        Arrays.sort(numbers);
        System.out.println("Sorted array: " + Arrays.toString(numbers));
        
        // Sort strings
        String[] names = {"John", "Alice", "Bob", "Zoe", "Mike"};
        Arrays.sort(names);
        System.out.println("Sorted names: " + Arrays.toString(names));
    }
}
Output:
Original array: [42, 13, 7, 25, 30, 18]
Sorted array: [7, 13, 18, 25, 30, 42]
Sorted names: [Alice, Bob, John, Mike, Zoe]

Searching Arrays:

Binary Search
import java.util.Arrays;

public class ArraySearch {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50, 60, 70};
        
        // Array must be sorted for binary search
        int index = Arrays.binarySearch(numbers, 40);
        System.out.println("Index of 40: " + index);
        
        index = Arrays.binarySearch(numbers, 35);
        System.out.println("Index of 35: " + index); // Negative value = not found
        
        // Linear search example
        int target = 50;
        int linearIndex = -1;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                linearIndex = i;
                break;
            }
        }
        System.out.println("Linear search for 50: " + linearIndex);
    }
}
Output:
Index of 40: 3
Index of 35: -4
Linear search for 50: 4
String Class

Strings are objects in Java that represent sequences of characters. They are immutable.

Common String Methods:

String Manipulation
public class StringMethods {
    public static void main(String[] args) {
        String text = "Hello, Java World!";
        
        // Length
        System.out.println("Length: " + text.length());
        
        // Substring
        System.out.println("Substring (7-11): " + text.substring(7, 11));
        
        // IndexOf
        System.out.println("Index of 'Java': " + text.indexOf("Java"));
        
        // Case conversion
        System.out.println("Uppercase: " + text.toUpperCase());
        System.out.println("Lowercase: " + text.toLowerCase());
        
        // Replace
        System.out.println("Replace 'World' with 'Programmers': " + 
            text.replace("World", "Programmers"));
        
        // Trim
        String spaced = "   Trim me!   ";
        System.out.println("Trimmed: '" + spaced.trim() + "'");
        
        // Split
        String[] words = text.split(" ");
        System.out.println("Split words: " + java.util.Arrays.toString(words));
    }
}
Output:
Length: 18
Substring (7-11): Java
Index of 'Java': 7
Uppercase: HELLO, JAVA WORLD!
Lowercase: hello, java world!
Replace 'World' with 'Programmers': Hello, Java Programmers!
Trimmed: 'Trim me!'
Split words: [Hello,, Java, World!]
0
H
1
e
2
l
3
l
4
o
5
,
6
7
J
StringBuilder & StringBuffer

For mutable string operations, Java provides StringBuilder (non-synchronized) and StringBuffer (synchronized).

StringBuilder Example:

StringBuilder Usage
public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        
        // Append methods
        sb.append("Hello");
        sb.append(" ");
        sb.append("Java");
        sb.append("!");
        
        System.out.println("String: " + sb.toString());
        
        // Insert
        sb.insert(5, ", World");
        System.out.println("After insert: " + sb);
        
        // Replace
        sb.replace(12, 16, "Programming");
        System.out.println("After replace: " + sb);
        
        // Delete
        sb.delete(0, 6);
        System.out.println("After delete: " + sb);
        
        // Reverse
        sb.reverse();
        System.out.println("Reversed: " + sb);
    }
}
Output:
String: Hello Java!
After insert: Hello, WorldJava!
After replace: Hello, WorldProgramming!
After delete: WorldProgramming!
Reversed: !gnimmargorPdlroW

String vs StringBuilder vs StringBuffer:

Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread Safety Thread-safe Not thread-safe Thread-safe
Performance Slow for modifications Fast Slower than StringBuilder
Storage String Pool Heap Heap
When to Use When immutability is required Single-threaded environments Multi-threaded environments

Recommendation: Use String for constants and when immutability is needed. Use StringBuilder for most string manipulation in single-threaded environments. Use StringBuffer only when thread safety is required.

Go Back

Next page