Beginner String Problems Java

String Programs in Java with Output

Write the basic string programs in Java that practice tests and interviews ask first.

  • TimeO(n) for each program,
  • SpaceO(1) for counting and palindrome, O(n) for reverse and uppercase
  • Hints3
  • Read3 min
Quick answer

Most string programs in Java loop over the characters with charAt(i) from 0 to length() - 1. To count vowels, check each character against "aeiou". To reverse, loop from the end and append to a StringBuilder. To check a palindrome, compare characters from both ends. Strings in Java are immutable, so build any new text with StringBuilder.

charAt and lengthStringBuilderTwo pointersFrequency array
1

Problem statement

Practise these string programs in Java on the word "Programming":

  1. find the length,
  2. count the vowels,
  3. reverse the string,
  4. count how many times a character appears, and
  5. check whether a word is a palindrome.

Four more programs (character frequency, word count, vowels and consonants, uppercase without built-ins) are in the solution section.

Input

A string s.

Output

The result of each program, one per line.

Examples

Example 1
Inputs = "Programming"
OutputLength 11, Vowels 3, Reversed "gnimmargorP"

The vowels are o, a and i.

Example 2
Inputs = "madam"
OutputPalindrome: true

m-a-d-a-m reads the same from both ends.

Constraints

  • 0 <= s.length() <= 10^5
  • The frequency program assumes lowercase letters a to z
2

Think before you code

Reveal the questions to ask yourself first
  • How do you get the character at position i?
  • Should "A" count as a vowel? How do you handle both cases?
  • Why is adding to a String in a loop slow, and what is the fix?
3

Hints

Open one at a time — try again after each.
1 Hint 1
s.charAt(i) gives one char. s.length() gives the count. Note the brackets: length() for String, length for arrays.
2 Hint 2
Call toLowerCase() once, then compare with lowercase letters only.
3 Hint 3
"aeiou".indexOf(ch) != -1 is a short way to test if ch is a vowel.
4

Approach

Reveal the step-by-step approach

The pattern behind string programs

Program Loop What to do with each char
Count vowels 0 to end if vowel, count++
Reverse end to 0 append to StringBuilder
Palindrome both ends inwards if chars differ, return false
Count one char 0 to end if equal to target, count++
Frequency 0 to end freq[ch - 'a']++

Why StringBuilder

A Java String cannot change. s = s + ch creates a new String each time. StringBuilder.append() changes one object, which is faster in loops.

For the full list of methods, see Java string methods and strings in Java.

5

Dry run

Walk through the example step by step

Count vowels in "Programming" after toLowerCase():

char | vowel? | count
-----+--------+------
p    | no     | 0
r    | no     | 0
o    | yes    | 1
g    | no     | 1
r    | no     | 1
a    | yes    | 2
m    | no     | 2
m    | no     | 2
i    | yes    | 3
n    | no     | 3
g    | no     | 3
6

Solution

Reveal the full Java solution
Solution.java
public class StringPrograms {
    // Count vowels (a, e, i, o, u) in any case
    static int countVowels(String s) {
        int count = 0;
        for (char ch : s.toLowerCase().toCharArray()) {
            if ("aeiou".indexOf(ch) != -1) {
                count++;
            }
        }
        return count;
    }

    static String reverse(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = s.length() - 1; i >= 0; i--) {
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }

    static boolean isPalindrome(String s) {
        int left = 0, right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    static int countChar(String s, char target) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == target) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String s = "Programming";
        System.out.println("String     : " + s);
        System.out.println("Length     : " + s.length());
        System.out.println("Vowels     : " + countVowels(s));
        System.out.println("Reversed   : " + reverse(s));
        System.out.println("Count of g : " + countChar(s, 'g'));
        System.out.println("madam palindrome? " + isPalindrome("madam"));
        System.out.println("java palindrome?  " + isPalindrome("java"));
    }
}

Output:

String     : Programming
Length     : 11
Vowels     : 3
Reversed   : gnimmargorP
Count of g : 2
madam palindrome? true
java palindrome?  false
  • Length: length() counts every character, including spaces.
  • Count vowels in Java: lowercase the string once, then test each char.
  • Reverse: the loop starts at length() - 1. new StringBuilder(s).reverse() is the built-in shortcut.
  • Palindrome: stops at the first mismatch. "java" fails at once because j is not a.
  • Count of g: the check is case-sensitive, so 'G' would not be counted.

String manipulation programs: four more

public class MoreStrings {
    public static void main(String[] args) {
        // 6. Frequency of each character
        String s = "banana";
        int[] freq = new int[26];
        for (char ch : s.toCharArray()) {
            freq[ch - 'a']++;
        }
        for (int i = 0; i < 26; i++) {
            if (freq[i] > 0) {
                System.out.println((char) ('a' + i) + " = " + freq[i]);
            }
        }

        // 7. Count words
        String line = "  Java is   easy to learn ";
        String[] words = line.trim().split("\\s+");
        System.out.println("Words: " + words.length);

        // 8. Vowels and consonants
        String t = "Hello World";
        int vowels = 0, consonants = 0;
        for (char ch : t.toLowerCase().toCharArray()) {
            if (ch >= 'a' && ch <= 'z') {
                if ("aeiou".indexOf(ch) != -1) {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }
        System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);

        // 9. Uppercase without toUpperCase()
        String word = "java";
        StringBuilder up = new StringBuilder();
        for (char ch : word.toCharArray()) {
            if (ch >= 'a' && ch <= 'z') {
                up.append((char) (ch - 32));
            } else {
                up.append(ch);
            }
        }
        System.out.println(up);
    }
}
a = 3
b = 1
n = 2
Words: 5
Vowels: 3, Consonants: 7
JAVA
  • Frequency: ch - 'a' turns a to 0, b to 1 and so on, so each letter gets its own slot in the array.
  • Word count: trim() removes the outer spaces and \\s+ splits on one or more spaces, so extra spaces do not create empty words.
  • Vowels and consonants: the range check skips the space in "Hello World".
  • Uppercase: in ASCII, 'a' is 97 and 'A' is 65, so subtract 32.

Java string practice questions to try next

For arrays, see array programs in Java. Many of these are also asked in Java string handling interviews.

TimeO(n) for each program, where n is the string length
SpaceO(1) for counting and palindrome, O(n) for reverse and uppercase
7

Review before the interview

Common mistakes

  • Comparing strings with == instead of equals(). == checks if both are the same object.
  • Writing s.length without brackets. For a String it is a method: s.length().
  • Building a reversed string with s = s + ch in a loop, which creates many objects.
  • Forgetting uppercase vowels, so "Apple" shows 1 vowel instead of 2.

Edge cases to test

  • Empty string: length 0, no vowels, reverse is empty, and it counts as a palindrome.
  • Spaces and digits: decide whether to count them. The vowel-consonant program skips them.
  • freq[ch - 'a'] fails for capitals or symbols. Lowercase first, or use int[256].
  • A line of only spaces: trim() makes it empty, and "".split("\\s+") gives one empty word. Check for empty first.

Interview follow-ups

  • How would you check a palindrome sentence that ignores spaces and case?
  • How would you find the most frequent character?
  • Why are Java strings immutable?

Keep practising

Practising for Java interviews?

CodeBegun’s Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us