String Programs in Java with Output
Write the basic string programs in Java that practice tests and interviews ask first.
- Time
O(n) for each program, - Space
O(1) for counting and palindrome, O(n) for reverse and uppercase - Hints3
- Read3 min
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.
Problem statement
Practise these string programs in Java on the word "Programming":
- find the length,
- count the vowels,
- reverse the string,
- count how many times a character appears, and
- 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.
A string s.
The result of each program, one per line.
Examples
s = "Programming"Length 11, Vowels 3, Reversed "gnimmargorP"The vowels are o, a and i.
s = "madam"Palindrome: truem-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
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?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
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.
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
Solution
Reveal the full Java solution
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.
O(n) for each program, where n is the string lengthO(1) for counting and palindrome, O(n) for reverse and uppercaseReview 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
Count the Vowels and Consonants in a String
Hints · Dry run · SolutionSolve Similar problemCheck Whether a String Is a Palindrome
Hints · Dry run · SolutionSolve Similar problemCount the Frequency of Each Character in a String
Hints · Dry run · SolutionSolve Similar problemReverse a String Without Using Built-in Methods
Hints · Dry run · SolutionSolve Related learningStrings
TutorialLearn Related learningJava String Methods
TutorialLearn Related learningString Handling
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun’s Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
