---
title: "String and Array Programs in Java (33, with Output)"
description: "33 string and array programs in Java for practice and interviews: two pointers, sliding window, hashing and Kadane, each with output and complexity."
slug: string-and-array-programs-in-java
canonical: https://learn.modernagecoders.com/blog/string-and-array-programs-in-java/
date: 2026-11-15
dateModified: 2026-11-15
category: "Java"
tags: ["Java", "Strings", "Arrays", "Interview Preparation", "Data Structures"]
keywords: ["string and array programs in java", "string programs in java", "array programs in java", "java string interview questions", "java array interview questions", "string programs in java for interview", "array programs in java for practice", "java coding questions for practice"]
readTime: "22 min read"
author: "Modern Age Coders Team"
---
# String and Array Programs in Java, with Output

> 33 programs for practice and interviews, grouped by the technique each one teaches, with the time complexity and real output for every solution.

![String and array programs in Java for practice and interviews, with output](/images/blog/string-and-array-programs-in-java/00-hero.png)

*By Modern Age Coders Team · 2026-11-15 · 22 min read*

**Quick answer:** The string and array programs in Java worth practising are the ones that teach a reusable technique: two pointers, a frequency count, a sliding window, hashing or a running total. This page solves 33 of them, 16 on strings and 17 on arrays, each with the idea, its time complexity and the exact output from running it on Java 21, grouped so you can practise by pattern for interviews.

The **string and array programs in Java** worth practising are the ones that teach a reusable technique: two pointers, a frequency count, a sliding window, a running total or a hash map lookup. Below are 33 of them, 16 on strings and 17 on arrays, each with the idea behind it, its time complexity, and the exact output from compiling it with javac and running it on Java 21. Work through them in order and most interview questions on strings and arrays will look like a variation of something you have already written.

This page is for anyone practising Java: students, self learners and people preparing for coding interviews or placement tests. If you are an ICSE student revising for the board exam, our board specific pages are a better fit: [ICSE Class 10 string programs](/icse-class-10-string-programs) and [ICSE Class 10 2D array programs](/icse-class-10-2d-array-programs) follow the exam's question style exactly. For a gentler start on arrays, see [Java array programs for beginners](/blog/java-array-programs-for-beginners), and for the String class itself, [string handling in Java](/blog/string-handling-in-java).

## Five techniques behind almost every program

Interviewers rarely want a memorised answer. They want to see you recognise which technique a problem needs. Nearly every string and array question here uses one of five:

| Technique | The idea | Programs that use it |
| --- | --- | --- |
| Two pointers | One index from each end, or a slow and a fast index, moving towards an answer | Reverse, palindrome, remove duplicates, move zeros, pair sum |
| Frequency count | An int[26] or int[256] array (or a HashMap) counting how often each value appears | Anagram, first unique character, character frequency, element frequency |
| Sliding window | A range [left, right] that grows on the right and shrinks on the left | Longest substring without repeats |
| Hashing | A HashMap or HashSet that answers have I seen this? in constant time | Two sum, intersection, duplicates |
| Running total | Carry one value forward as you scan once: a sum, a best so far, a maximum from the right | Kadane, prefix sums, leaders, second largest, majority vote |

![Five techniques behind string and array programs in Java: two pointers, frequency count, sliding window, hashing and running total, each with a tiny example](/images/blog/string-and-array-programs-in-java/01-techniques.png)

*Spot the technique first. The code is the easy part once you know which one the problem wants.*

> **Brute force first, then improve**

> In an interview, say the simple nested loop solution out loud with its complexity, then improve it. Showing the step from O(n²) to O(n) is worth more than jumping straight to a clever answer you cannot explain.

## String programs in Java

Java Strings are immutable: every method that seems to change one, such as `toUpperCase()` or `replace()`, returns a new String. When a program builds a string piece by piece, use a `StringBuilder`, which changes in place and avoids creating a new object on every step.

### 1. Reverse a string

**Question:** Reverse a string in two ways: with StringBuilder and with a two pointer swap on a char array.

```java
public class ReverseString {
    static String reverse(String s) {
        char[] c = s.toCharArray();
        int i = 0, j = c.length - 1;
        while (i < j) {
            char t = c[i];
            c[i++] = c[j];
            c[j--] = t;
        }
        return new String(c);
    }

    public static void main(String[] args) {
        String s = "interview";
        System.out.println(new StringBuilder(s).reverse());
        System.out.println(reverse(s));
    }
}
```

**Output**

```text
weivretni
weivretni
```

**How it works:** Swap the outermost pair and move both pointers inward until they meet. **Time:** O(n), extra space O(n) for the char array.

### 2. Palindrome check ignoring case and punctuation

**Question:** Check whether a sentence is a palindrome, ignoring spaces, punctuation and case.

```java
public class PalindromeSentence {
    static boolean isPalindrome(String s) {
        int i = 0, j = s.length() - 1;
        while (i < j) {
            char a = s.charAt(i), b = s.charAt(j);
            if (!Character.isLetterOrDigit(a)) { i++; continue; }
            if (!Character.isLetterOrDigit(b)) { j--; continue; }
            if (Character.toLowerCase(a) != Character.toLowerCase(b))
                return false;
            i++;
            j--;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("A man, a plan, a canal: Panama"));
        System.out.println(isPalindrome("race a car"));
    }
}
```

**Output**

```text
true
false
```

**How it works:** Two pointers skip anything that is not a letter or digit and compare the rest case insensitively, without building a cleaned copy. **Time:** O(n), extra space O(1).

### 3. Count vowels, consonants, digits and spaces

**Question:** Count the vowels, consonants, digits, spaces and other characters in a sentence.

```java
public class CharTypes {
    public static void main(String[] args) {
        String s = "Java 21 shipped in September 2023!";
        int v = 0, c = 0, d = 0, sp = 0, other = 0;
        for (char ch : s.toLowerCase().toCharArray()) {
            if ("aeiou".indexOf(ch) >= 0) v++;
            else if (ch >= 'a' && ch <= 'z') c++;
            else if (Character.isDigit(ch)) d++;
            else if (ch == ' ') sp++;
            else other++;
        }
        System.out.println("Vowels: " + v + ", consonants: " + c + ", digits: " + d
                + ", spaces: " + sp + ", other: " + other);
    }
}
```

**Output**

```text
Vowels: 8, consonants: 14, digits: 6, spaces: 5, other: 1
```

### 4. Character frequency

**Question:** Print how many times each character occurs in a word, in order of first appearance.

```java
import java.util.LinkedHashMap;
import java.util.Map;

public class CharFrequency {
    public static void main(String[] args) {
        String s = "programming";
        Map<Character, Integer> freq = new LinkedHashMap<>();
        for (char c : s.toCharArray())
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        System.out.println(freq);
    }
}
```

**Output**

```text
{p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}
```

**How it works:** A LinkedHashMap counts each character and keeps insertion order, so the output follows the word. **Time:** O(n).

### 5. First non-repeating character

**Question:** Find the first character in a string that does not repeat.

```java
public class FirstUnique {
    static char firstUnique(String s) {
        int[] count = new int[26];
        for (char c : s.toCharArray())
            count[c - 'a']++;
        for (char c : s.toCharArray())
            if (count[c - 'a'] == 1)
                return c;
        return '_';
    }

    public static void main(String[] args) {
        System.out.println(firstUnique("swiss"));
        System.out.println(firstUnique("aabbcc"));
        System.out.println(firstUnique("loveleetcode"));
    }
}
```

**Output**

```text
w
_
v
```

**How it works:** Two passes: the first counts every letter in an int[26], the second returns the first letter whose count is 1. An underscore means there is none. **Time:** O(n), extra space O(1) because the array size is fixed.

### 6. Anagram check with a count array

**Question:** Check whether two strings are anagrams without sorting.

```java
public class AnagramCount {
    static boolean isAnagram(String a, String b) {
        if (a.length() != b.length())
            return false;
        int[] count = new int[26];
        for (int i = 0; i < a.length(); i++) {
            count[a.charAt(i) - 'a']++;
            count[b.charAt(i) - 'a']--;
        }
        for (int x : count)
            if (x != 0)
                return false;
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("listen", "silent"));
        System.out.println(isAnagram("rat", "car"));
    }
}
```

**Output**

```text
true
false
```

**How it works:** Add one for each letter of the first word and subtract one for each letter of the second. Anagrams leave every count at zero. Sorting both words also works but costs O(n log n). **Time:** O(n).

### 7. Remove duplicate characters

**Question:** Remove repeated characters from a string, keeping the first occurrence of each.

```java
public class RemoveDupChars {
    public static void main(String[] args) {
        String s = "bananas and apples";
        boolean[] seen = new boolean[256];
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (!seen[c]) {
                seen[c] = true;
                sb.append(c);
            }
        }
        System.out.println(sb);
    }
}
```

**Output**

```text
bans dple
```

### 8. Reverse the words in a sentence

**Question:** Reverse the order of words in a sentence, collapsing extra spaces.

```java
public class ReverseWords {
    public static void main(String[] args) {
        String s = "  the sky   is blue ";
        String[] words = s.trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            sb.append(words[i]);
            if (i > 0)
                sb.append(' ');
        }
        System.out.println("[" + sb + "]");
    }
}
```

**Output**

```text
[blue is sky the]
```

**How it works:** trim() removes the outer spaces and split("\\s+") treats any run of spaces as one separator. The square brackets in the output show there are no stray spaces left. **Time:** O(n).

### 9. Check if one string is a rotation of another

**Question:** Check whether s2 is a rotation of s1, for example waterbottle and erbottlewat.

```java
public class Rotation {
    static boolean isRotation(String a, String b) {
        return a.length() == b.length() && (a + a).contains(b);
    }

    public static void main(String[] args) {
        System.out.println(isRotation("waterbottle", "erbottlewat"));
        System.out.println(isRotation("hello", "lohel"));
        System.out.println(isRotation("hello", "olleh"));
    }
}
```

**Output**

```text
true
true
false
```

**How it works:** Every rotation of a string appears inside that string written twice. One line, once you see it. **Time:** O(n) on average for contains.

### 10. Longest substring without repeating characters

**Question:** Find the length of the longest substring with no repeated character.

```java
import java.util.HashMap;
import java.util.Map;

public class LongestUnique {
    static String longest(String s) {
        Map<Character, Integer> last = new HashMap<>();
        int left = 0, bestLen = 0, bestStart = 0;
        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            if (last.containsKey(c) && last.get(c) >= left)
                left = last.get(c) + 1;
            last.put(c, right);
            if (right - left + 1 > bestLen) {
                bestLen = right - left + 1;
                bestStart = left;
            }
        }
        return s.substring(bestStart, bestStart + bestLen);
    }

    public static void main(String[] args) {
        String[] tests = {"abcabcbb", "bbbbb", "pwwkew"};
        for (String t : tests) {
            String r = longest(t);
            System.out.println(t + " -> " + r + " (length " + r.length() + ")");
        }
    }
}
```

**Output**

```text
abcabcbb -> abc (length 3)
bbbbb -> b (length 1)
pwwkew -> wke (length 3)
```

**How it works:** A sliding window [left, right]. When the new character was already seen inside the window, jump left past its last position. The window never moves backwards. **Time:** O(n).

### 11. String compression

**Question:** Compress a string by replacing runs of the same character with the character and its count, for example aaabbc becomes a3b2c1. Return the original if the result is not shorter.

```java
public class Compress {
    static String compress(String s) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < s.length()) {
            char c = s.charAt(i);
            int j = i;
            while (j < s.length() && s.charAt(j) == c)
                j++;
            sb.append(c).append(j - i);
            i = j;
        }
        return sb.length() < s.length() ? sb.toString() : s;
    }

    public static void main(String[] args) {
        System.out.println(compress("aaabbbbcccd"));
        System.out.println(compress("abc"));
    }
}
```

**Output**

```text
a3b4c3d1
abc
```

### 12. Toggle case and capitalise words

**Question:** Toggle the case of every letter, then capitalise the first letter of each word.

```java
public class CaseTools {
    public static void main(String[] args) {
        String s = "hello World from jAVA";
        StringBuilder t = new StringBuilder();
        for (char c : s.toCharArray())
            t.append(Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c));
        System.out.println(t);

        StringBuilder cap = new StringBuilder();
        for (String w : s.toLowerCase().split(" "))
            cap.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1)).append(' ');
        System.out.println(cap.toString().trim());
    }
}
```

**Output**

```text
HELLO wORLD FROM Java
Hello World From Java
```

### 13. Longest common prefix

**Question:** Find the longest common prefix of an array of strings.

```java
public class CommonPrefix {
    static String prefix(String[] words) {
        String p = words[0];
        for (String w : words)
            while (!w.startsWith(p))
                p = p.substring(0, p.length() - 1);
        return p;
    }

    public static void main(String[] args) {
        System.out.println("[" + prefix(new String[]{"flower", "flow", "flight"}) + "]");
        System.out.println("[" + prefix(new String[]{"interview", "internet", "interval"}) + "]");
        System.out.println("[" + prefix(new String[]{"dog", "car"}) + "]");
    }
}
```

**Output**

```text
[fl]
[inter]
[]
```

**How it works:** Start with the first word as the candidate and shorten it until every word starts with it. Empty brackets mean no common prefix. **Time:** O(total characters).

### 14. Balanced brackets

**Question:** Check whether a string of brackets is balanced, using a stack.

```java
import java.util.ArrayDeque;
import java.util.Deque;

public class Brackets {
    static boolean balanced(String s) {
        Deque<Character> st = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{')
                st.push(c);
            else {
                if (st.isEmpty()) return false;
                char o = st.pop();
                if ((c == ')' && o != '(') || (c == ']' && o != '[') || (c == '}' && o != '{'))
                    return false;
            }
        }
        return st.isEmpty();
    }

    public static void main(String[] args) {
        String[] tests = {"{[()]}", "([)]", "((()", "()[]{}"};
        for (String t : tests)
            System.out.println(t + " -> " + balanced(t));
    }
}
```

**Output**

```text
{[()]} -> true
([)] -> false
((() -> false
()[]{} -> true
```

**How it works:** Push every opening bracket; every closing bracket must match the most recent one still open. ArrayDeque is the recommended stack in modern Java, faster than the older Stack class. **Time:** O(n).

### 15. Count words and find the longest

**Question:** Count the words in a sentence and print the longest one.

```java
public class WordStats {
    public static void main(String[] args) {
        String s = "Practice makes progress, not perfection";
        String[] words = s.replaceAll("[^A-Za-z ]", "").split(" ");
        String longest = "";
        for (String w : words)
            if (w.length() > longest.length())
                longest = w;
        System.out.println("Words: " + words.length);
        System.out.println("Longest: " + longest + " (" + longest.length() + " letters)");
    }
}
```

**Output**

```text
Words: 5
Longest: perfection (10 letters)
```

### 16. Check if a string is a number, and convert it

**Question:** Check whether a string contains only digits, then convert it to an int without Integer.parseInt.

```java
public class ParseDigits {
    static int toInt(String s) {
        int n = 0;
        for (char c : s.toCharArray()) {
            if (c < '0' || c > '9')
                throw new IllegalArgumentException("not a number: " + s);
            n = n * 10 + (c - '0');
        }
        return n;
    }

    public static void main(String[] args) {
        System.out.println(toInt("4096") + 4);
        try {
            toInt("40a6");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
```

**Output**

```text
4100
not a number: 40a6
```

**How it works:** Each character minus '0' is its digit value, and n * 10 + digit builds the number left to right, the digit extraction used to reverse a number, run the other way. **Time:** O(n).

## Array programs in Java

Arrays in Java have a fixed length, are indexed from 0 to `length - 1`, and are filled with default values (0, false or null) when created. `Arrays.toString()` prints a one dimensional array, which is how the outputs below are shown.

### 17. Largest, smallest and second largest in one pass

**Question:** Find the largest, smallest and second largest element of an array in a single scan.

```java
public class MinMaxSecond {
    public static void main(String[] args) {
        int[] a = {12, 35, 1, 10, 34, 35, 1};
        int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
        for (int x : a) {
            if (x > max) {
                second = max;
                max = x;
            } else if (x > second && x != max) {
                second = x;
            }
            if (x < min)
                min = x;
        }
        System.out.println("Max = " + max + ", second = " + second + ", min = " + min);
    }
}
```

**Output**

```text
Max = 35, second = 34, min = 1
```

**How it works:** When a new maximum arrives, the old maximum becomes the second. The x != max check stops a repeated maximum (35 twice here) from being counted as the second largest. **Time:** O(n), one pass.

### 18. Reverse an array in place

**Question:** Reverse an array without using a second array.

```java
import java.util.Arrays;

public class ReverseArray {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6};
        for (int i = 0, j = a.length - 1; i < j; i++, j--) {
            int t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
        System.out.println(Arrays.toString(a));
    }
}
```

**Output**

```text
[6, 5, 4, 3, 2, 1]
```

### 19. Rotate an array by k places

**Question:** Rotate an array to the right by k = 3 positions using the reversal method.

```java
import java.util.Arrays;

public class RotateArray {
    static void reverse(int[] a, int i, int j) {
        while (i < j) {
            int t = a[i];
            a[i++] = a[j];
            a[j--] = t;
        }
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7};
        int k = 3 % a.length;
        reverse(a, 0, a.length - 1);
        reverse(a, 0, k - 1);
        reverse(a, k, a.length - 1);
        System.out.println(Arrays.toString(a));
    }
}
```

**Output**

```text
[5, 6, 7, 1, 2, 3, 4]
```

**How it works:** Reverse the whole array, then reverse the first k and the remaining n - k separately. Three reversals, no extra array. **Time:** O(n), extra space O(1).

### 20. Remove duplicates from a sorted array

**Question:** Remove duplicates from a sorted array in place and return the new length.

```java
import java.util.Arrays;

public class DedupSorted {
    public static void main(String[] args) {
        int[] a = {1, 1, 2, 3, 3, 3, 4, 5, 5};
        int w = 1;   // write position
        for (int r = 1; r < a.length; r++)
            if (a[r] != a[w - 1])
                a[w++] = a[r];
        System.out.println("New length = " + w);
        System.out.println(Arrays.toString(Arrays.copyOf(a, w)));
    }
}
```

**Output**

```text
New length = 5
[1, 2, 3, 4, 5]
```

**How it works:** A slow write pointer and a fast read pointer. Because the array is sorted, a value is new only if it differs from the last value written. **Time:** O(n), extra space O(1).

### 21. Move all zeros to the end

**Question:** Move all zeros to the end of an array while keeping the order of the other elements.

```java
import java.util.Arrays;

public class MoveZeros {
    public static void main(String[] args) {
        int[] a = {0, 1, 0, 3, 12, 0, 7};
        int w = 0;
        for (int x : a)
            if (x != 0)
                a[w++] = x;
        while (w < a.length)
            a[w++] = 0;
        System.out.println(Arrays.toString(a));
    }
}
```

**Output**

```text
[1, 3, 12, 7, 0, 0, 0]
```

### 22. Two sum with a HashMap

**Question:** Find the indices of two numbers in an unsorted array that add up to a target.

```java
import java.util.HashMap;
import java.util.Map;

public class TwoSum {
    public static void main(String[] args) {
        int[] a = {8, 3, 11, 5, 2, 7};
        int target = 9;
        Map<Integer, Integer> seen = new HashMap<>();
        for (int i = 0; i < a.length; i++) {
            int need = target - a[i];
            if (seen.containsKey(need)) {
                System.out.println("Indices " + seen.get(need) + " and " + i
                        + " (" + need + " + " + a[i] + " = " + target + ")");
                return;
            }
            seen.put(a[i], i);
        }
        System.out.println("No pair found");
    }
}
```

**Output**

```text
Indices 4 and 5 (2 + 7 = 9)
```

**How it works:** For each number, ask whether its partner (target minus the number) has been seen already. The nested loop version checks every pair and takes O(n²). **Time:** O(n), extra space O(n).

### 23. Pair with a given sum in a sorted array

**Question:** In a sorted array, find a pair that adds up to a target using two pointers.

```java
public class PairSorted {
    public static void main(String[] args) {
        int[] a = {1, 4, 6, 8, 11, 15};
        int target = 19, i = 0, j = a.length - 1;
        while (i < j) {
            int s = a[i] + a[j];
            if (s == target) {
                System.out.println(a[i] + " + " + a[j] + " = " + target);
                break;
            } else if (s < target)
                i++;
            else
                j--;
        }
    }
}
```

**Output**

```text
4 + 15 = 19
```

**How it works:** If the sum is too small, only moving the left pointer right can increase it; if too large, move the right pointer left. Sorting is what makes this safe. **Time:** O(n), extra space O(1).

### 24. Find the missing number

**Question:** An array holds the numbers 1 to n with one missing. Find it.

```java
public class MissingNumber {
    public static void main(String[] args) {
        int[] a = {1, 2, 4, 6, 3, 7, 8};
        int n = a.length + 1;
        long expected = (long) n * (n + 1) / 2;
        long sum = 0;
        for (int x : a)
            sum += x;
        System.out.println("Missing = " + (expected - sum));
    }
}
```

**Output**

```text
Missing = 5
```

**How it works:** The sum of 1 to n is n(n + 1)/2. Whatever the array falls short by is the missing number. Using long avoids overflow for large n. **Time:** O(n).

### 25. Maximum subarray sum (Kadane's algorithm)

**Question:** Find the contiguous subarray with the largest sum, and print it.

```java
import java.util.Arrays;

public class Kadane {
    public static void main(String[] args) {
        int[] a = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        int best = a[0], cur = a[0], start = 0, bestStart = 0, bestEnd = 0;
        for (int i = 1; i < a.length; i++) {
            if (cur + a[i] < a[i]) {
                cur = a[i];
                start = i;
            } else {
                cur += a[i];
            }
            if (cur > best) {
                best = cur;
                bestStart = start;
                bestEnd = i;
            }
        }
        System.out.println("Max sum = " + best);
        System.out.println("Subarray = " + Arrays.toString(Arrays.copyOfRange(a, bestStart, bestEnd + 1)));
    }
}
```

**Output**

```text
Max sum = 6
Subarray = [4, -1, 2, 1]
```

**How it works:** Carry a running sum. If the running sum plus the next element is worse than starting fresh at that element, start fresh. Track the best seen. **Time:** O(n), one pass.

### 26. Merge two sorted arrays

**Question:** Merge two sorted arrays into one sorted array.

```java
import java.util.Arrays;

public class MergeSorted {
    public static void main(String[] args) {
        int[] a = {1, 4, 7, 10}, b = {2, 3, 8, 12, 15};
        int[] m = new int[a.length + b.length];
        int i = 0, j = 0, k = 0;
        while (i < a.length && j < b.length)
            m[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];
        while (i < a.length) m[k++] = a[i++];
        while (j < b.length) m[k++] = b[j++];
        System.out.println(Arrays.toString(m));
    }
}
```

**Output**

```text
[1, 2, 3, 4, 7, 8, 10, 12, 15]
```

**How it works:** Compare the fronts of both arrays and take the smaller each time, then copy whatever is left. This is the merge step inside merge sort. **Time:** O(n + m).

### 27. Frequency of each element

**Question:** Count how often each element occurs in an array.

```java
import java.util.Map;
import java.util.TreeMap;

public class ElementFrequency {
    public static void main(String[] args) {
        int[] a = {4, 2, 4, 9, 2, 4, 7};
        Map<Integer, Integer> f = new TreeMap<>();
        for (int x : a)
            f.merge(x, 1, Integer::sum);
        f.forEach((k, v) -> System.out.println(k + " occurs " + v + " time(s)"));
    }
}
```

**Output**

```text
2 occurs 2 time(s)
4 occurs 3 time(s)
7 occurs 1 time(s)
9 occurs 1 time(s)
```

**How it works:** A TreeMap keeps keys sorted, so the output comes in ascending order. merge(x, 1, Integer::sum) inserts 1 or adds 1 to the existing count. **Time:** O(n log n) with TreeMap, O(n) with HashMap.

### 28. Majority element (Boyer-Moore voting)

**Question:** Find the element that appears more than half the time, using constant extra space.

```java
public class Majority {
    public static void main(String[] args) {
        int[] a = {2, 2, 1, 1, 2, 3, 2};
        int cand = 0, count = 0;
        for (int x : a) {
            if (count == 0)
                cand = x;
            count += (x == cand) ? 1 : -1;
        }
        int occurs = 0;
        for (int x : a)
            if (x == cand)
                occurs++;
        System.out.println(occurs > a.length / 2 ? "Majority = " + cand : "No majority");
    }
}
```

**Output**

```text
Majority = 2
```

**How it works:** Pair each majority vote with a different vote and cancel them. A true majority survives the cancelling. The second loop confirms it, since some arrays have no majority. **Time:** O(n), extra space O(1).

### 29. Leaders in an array

**Question:** An element is a leader if it is greater than every element to its right. Print all leaders.

```java
public class Leaders {
    public static void main(String[] args) {
        int[] a = {16, 17, 4, 3, 5, 2};
        int maxRight = Integer.MIN_VALUE;
        StringBuilder sb = new StringBuilder();
        for (int i = a.length - 1; i >= 0; i--) {
            if (a[i] > maxRight) {
                maxRight = a[i];
                sb.insert(0, a[i] + " ");
            }
        }
        System.out.println(sb.toString().trim());
    }
}
```

**Output**

```text
17 5 2
```

**How it works:** Scan from the right, keeping the largest value seen so far. Any element bigger than that running maximum is a leader. **Time:** O(n).

### 30. Intersection of two arrays

**Question:** Print the common elements of two arrays, without repeats.

```java
import java.util.LinkedHashSet;
import java.util.Set;

public class Intersection {
    public static void main(String[] args) {
        int[] a = {4, 9, 5, 4, 1}, b = {9, 4, 9, 8, 4};
        Set<Integer> setA = new LinkedHashSet<>();
        for (int x : a) setA.add(x);
        Set<Integer> common = new LinkedHashSet<>();
        for (int x : b)
            if (setA.contains(x))
                common.add(x);
        System.out.println(common);
    }
}
```

**Output**

```text
[9, 4]
```

### 31. Prefix sums for range queries

**Question:** Build a prefix sum array and answer the sum of any range in constant time.

```java
public class PrefixSum {
    public static void main(String[] args) {
        int[] a = {3, 1, 4, 1, 5, 9, 2, 6};
        int[] p = new int[a.length + 1];
        for (int i = 0; i < a.length; i++)
            p[i + 1] = p[i] + a[i];
        int[][] queries = {{0, 3}, {2, 5}, {4, 7}};
        for (int[] q : queries)
            System.out.println("Sum of a[" + q[0] + ".." + q[1] + "] = " + (p[q[1] + 1] - p[q[0]]));
    }
}
```

**Output**

```text
Sum of a[0..3] = 9
Sum of a[2..5] = 19
Sum of a[4..7] = 22
```

**How it works:** p[i] holds the sum of the first i elements, so the sum from l to r is p[r + 1] - p[l]. One O(n) pass to build, then every query is O(1). **Time:** O(n) to build, O(1) per query.

### 32. Binary search (iterative)

**Question:** Search a sorted array for a key, returning its index or -1.

```java
public class BinSearch {
    static int search(int[] a, int key) {
        int lo = 0, hi = a.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == key) return mid;
            if (a[mid] < key) lo = mid + 1;
            else hi = mid - 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] a = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
        System.out.println(search(a, 23));
        System.out.println(search(a, 7));
    }
}
```

**Output**

```text
5
-1
```

**How it works:** Halve the search range each step. lo + (hi - lo) / 2 avoids the integer overflow that (lo + hi) / 2 can cause on very large arrays. **Time:** O(log n).

### 33. Spiral order of a matrix

**Question:** Print the elements of a 2D array in spiral order.

```java
import java.util.ArrayList;
import java.util.List;

public class Spiral {
    public static void main(String[] args) {
        int[][] m = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        List<Integer> out = new ArrayList<>();
        int top = 0, bottom = m.length - 1, left = 0, right = m[0].length - 1;
        while (top <= bottom && left <= right) {
            for (int j = left; j <= right; j++) out.add(m[top][j]);
            top++;
            for (int i = top; i <= bottom; i++) out.add(m[i][right]);
            right--;
            if (top <= bottom) {
                for (int j = right; j >= left; j--) out.add(m[bottom][j]);
                bottom--;
            }
            if (left <= right) {
                for (int i = bottom; i >= top; i--) out.add(m[i][left]);
                left++;
            }
        }
        System.out.println(out);
    }
}
```

**Output**

```text
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
```

**How it works:** Four boundaries close in after each side is printed. The two if checks stop a single remaining row or column from being printed twice. **Time:** O(rows x columns).

## How to practise these for interviews

Reading a solution feels like learning, but interviews test whether you can produce one under a little pressure. A routine that works:

1. **Read the problem and say the technique** before looking at any code: two pointers, frequency count, sliding window, hashing or running total.
2. **Write the brute force version** and state its complexity. It is your safety net.
3. **Improve it** and explain what the faster version trades: usually extra memory for less time.
4. **Test edge cases out loud**: an empty string or array, one element, all equal elements, negative numbers.
5. **Revisit after three days** without looking. If you cannot rewrite it, you memorised it rather than understood it.

![The sliding window on the string abcabcbb: the window grows to abc, then the repeated a moves the left edge past the first a, keeping the window free of repeats, with the best length 3](/images/blog/string-and-array-programs-in-java/02-sliding-window.png)

*The window only ever moves forward, which is why the whole scan is O(n).*

## String and array interview questions, by pattern

Grouping questions by technique is the quickest way to make them stick. Every question in this list is solved above:

| Pattern | Questions solved on this page |
| --- | --- |
| Two pointers | Reverse a string, palindrome sentence, reverse an array, remove duplicates from a sorted array, move zeros, pair with a given sum |
| Frequency count | Character frequency, first non-repeating character, anagram check, remove duplicate characters, element frequency |
| Sliding window | Longest substring without repeating characters, string compression (a run is a window) |
| Hashing | Two sum, intersection of two arrays |
| Running total | Second largest, missing number, Kadane, leaders, prefix sums, majority element |
| Stack or boundaries | Balanced brackets, spiral matrix |

![Two pointers on the sorted array 1, 4, 6, 8, 11, 15 looking for a pair that sums to 19: the sum 16 is too small so the left pointer moves right, then 4 + 15 = 19 is found](/images/blog/string-and-array-programs-in-java/03-two-pointers.png)

*Each comparison rules out one element for good, so the scan is linear.*

## Java string and array programs for beginners

If you are new to Java, start with programs 1, 3, 12 and 15 on strings and 17, 18 and 24 on arrays. They need only loops, if statements and `charAt()`. Then move to the frequency count programs (4, 5, 6), which introduce the most useful trick on the page. Leave sliding window, Kadane and spiral order until loops feel automatic.

> **Strings versus char arrays**

> String is immutable, so code that changes characters one at a time usually converts with toCharArray(), works on the array, and converts back with new String(chars). StringBuilder is the right tool when you are appending.

## How we teach it

In our classes a student explains their thinking before typing, and we trace a loop line by line until they can predict every step, which is exactly what the two pointer and sliding window figures above do on paper. Students derive the rule from small examples before seeing the code, solve the same problem three ways (nested loops, sorting, then hashing for the anagram check, for example), and treat every wrong output as data about where the reasoning slipped. You can see this on [how we teach](/how-we-teach), or look at our [Java DSA course](/java-dsa-course) for interview preparation and [Java for beginners](/java-for-beginners) if you are starting out. The first class is free: [book a free trial class](/free-trial).

---

## Frequently asked questions

**What are the most common string programs asked in Java interviews?**

Reversing a string, palindrome checks, anagram checks, character frequency, first non-repeating character, reversing words, string rotation, longest substring without repeating characters and balanced brackets. All of them are solved above with output.

**What are the most common array programs asked in Java interviews?**

Second largest element, reversing and rotating an array, removing duplicates, moving zeros, two sum, missing number, maximum subarray sum (Kadane), merging sorted arrays and binary search.

**How do I reverse a string in Java without using reverse()?**

Convert it to a char array, swap the first and last characters, move both indices inward and repeat until they meet, then build a new String from the array. Program 1 shows both this and the StringBuilder way.

**Why are Strings immutable in Java?**

A String object never changes after it is created, which makes Strings safe to share between parts of a program and between threads and lets Java reuse identical literals. Methods such as toUpperCase return a new String, so build strings in loops with StringBuilder.

**What is the difference between == and equals() for Strings?**

== checks whether two references point to the same object. equals() checks whether the characters are the same. Always compare String contents with equals(), or equalsIgnoreCase() when case should not matter.

**How should I practise string and array programs?**

Group them by technique, write each one without looking, state its time complexity, and test the edge cases: empty input, one element, repeated values and negatives. Revisit each a few days later to check it stuck.

**Are these the same as ICSE string and array programs?**

No. ICSE board questions follow a specific exam style, such as Piglatin words or matrix programs worded for BlueJ. For those, use our ICSE Class 10 string programs and ICSE Class 10 2D array programs pages. This page is for general practice and interviews.

**Do I need to know Big O for these programs?**

For interviews, yes: you will be asked the time and space cost of your solution. Each program here states it, so you can check your own estimate against it.

## Keep practising

Board exam students should switch to the [ICSE Class 10 string programs](/icse-class-10-string-programs) and the [ICSE Class 10 2D array programs](/icse-class-10-2d-array-programs), and ISC students will find recursion and data structures in our [Java programs for ISC Class 11 and 12](/blog/java-programs-for-isc-class-11-and-12). If you are preparing for placements, our [coding interview preparation guide for freshers](/blog/coding-interview-preparation-for-freshers) covers the rest of the process.

[Book a Free Java Class](/free-trial)

---

*Source: https://learn.modernagecoders.com/blog/string-and-array-programs-in-java/*
