Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Arrays and Strings in Java

Introduction

Arrays and strings are among the most frequently used data structures in Java. Arrays allow storing multiple values of the same type in a single variable, while strings are used to handle text data. Java provides powerful built-in classes such as String, StringBuilder, and StringBuffer to perform efficient text manipulation. Understanding these concepts is essential for real-world Java programming, problem solving, and interviews.


1. Single-Dimensional Arrays

Description

A single-dimensional array is a collection of elements of the same data type stored in contiguous memory locations. Each element can be accessed using an index, starting from 0.

Key Points

  • Fixed size once created
  • Stores same type of data
  • Index starts from 0
  • Faster access using index

Syntax

dataType[] arrayName = new dataType[size];

Example

int[] marks = new int[5];

marks[0] = 85;
marks[1] = 90;
marks[2] = 78;
marks[3] = 88;
marks[4] = 92;

System.out.println(marks[2]);

Explanation

The array marks stores 5 integer values. The value at index 2 is printed.


2. Multi-Dimensional Arrays

Description

A multi-dimensional array is an array of arrays. The most commonly used type is the two-dimensional array, which is represented in rows and columns like a table or matrix.

Key Points

  • Useful for matrix operations
  • Represent data in tabular form
  • Accessed using row and column index

Syntax

dataType[][] arrayName = new dataType[rows][columns];

Example

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6}
};

System.out.println(matrix[1][2]);

Explanation

The value at row index 1 and column index 2 is printed, which is 6.


3. Array Operations and Methods

Java provides the Arrays class in java.util package to perform common operations.

Common Array Operations

a) Traversing an Array

int[] numbers = {10, 20, 30, 40};

for (int num : numbers) {
    System.out.println(num);
}

b) Sorting an Array

import java.util.Arrays;

int[] nums = {5, 2, 8, 1};
Arrays.sort(nums);

System.out.println(Arrays.toString(nums));

c) Searching an Element

int index = Arrays.binarySearch(nums, 8);
System.out.println(index);

d) Copying an Array

int[] copy = Arrays.copyOf(nums, nums.length);

Important Array Methods

MethodDescription
sort()Sorts array
binarySearch()Searches element
copyOf()Copies array
equals()Compares arrays
toString()Prints array

4. String Class in Java

Description

The String class is used to represent a sequence of characters. In Java, strings are immutable, meaning once created, their values cannot be changed.

Key Points

  • Immutable in nature
  • Stored in String Constant Pool
  • Thread-safe
  • Uses equals() for comparison

Example

String name = "Java";
name = name.concat(" Programming");

System.out.println(name);

5. Common String Methods

Frequently Used Methods

String text = "Java Programming";
MethodExampleResult
length()text.length()Length
toUpperCase()text.toUpperCase()Uppercase
toLowerCase()text.toLowerCase()Lowercase
charAt()text.charAt(2)Character
substring()text.substring(5)Substring
contains()text.contains("Java")true/false
replace()text.replace("Java", "Core Java")Replaced

6. StringBuilder Class

Description

StringBuilder is used to create mutable strings. It is faster than String because it does not create new objects during modification.

Key Points

  • Mutable
  • Not thread-safe
  • Faster performance
  • Used in single-threaded applications

Example

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");

System.out.println(sb);

7. StringBuffer Class

Description

StringBuffer is similar to StringBuilder but is thread-safe.

Key Points

  • Mutable
  • Thread-safe
  • Slightly slower than StringBuilder
  • Used in multi-threaded applications

Example

StringBuffer sbf = new StringBuffer("Java");
sbf.append(" Course");

System.out.println(sbf);

8. String vs StringBuilder vs StringBuffer

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread SafetyYesNoYes
PerformanceSlowFastMedium
Use CaseFixed textSingle threadMulti-thread

9. String Manipulation

Description

String manipulation refers to operations performed on strings to modify, analyze, or extract data.

Common String Manipulation Examples

a) Reverse a String

String input = "Java";
StringBuilder rev = new StringBuilder(input);
System.out.println(rev.reverse());

b) Count Characters

String s = "Programming";
System.out.println(s.length());

c) Check Palindrome

String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();

if (str.equals(reversed)) {
    System.out.println("Palindrome");
} else {
    System.out.println("Not Palindrome");
}

d) Remove Spaces

String sentence = "Java is powerful";
System.out.println(sentence.replace(" ", ""));

Example:

java

public class ArraysAndStrings {
    public static void main(String[] args) {
        // Arrays
        int[] numbers = {10, 20, 30, 40, 50};
        System.out.println("First element: " + numbers[0]);
        
        // Loop through array
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println();
        
        // 2D Array
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println("Element at [1][2]: " + matrix[1][2]);
        
        // Strings
        String text = "Java Programming";
        System.out.println("Length: " + text.length());
        System.out.println("Uppercase: " + text.toUpperCase());
        System.out.println("Substring: " + text.substring(0, 4));
        System.out.println("Contains 'Java': " + text.contains("Java"));
        
        // StringBuilder for efficient string manipulation
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World");
        sb.insert(5, ",");
        System.out.println(sb.toString());
    }
}

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥