Common Java String Programs with Examples
Introduction
String-handling programs are a staple of Java practice, coding tests and interviews. This tutorial works through the common Java string programs every beginner should be able to write. We will start by reversing a string and checking for palindromes. We will then count vowels, consonants, words and the frequency of each character. Next we will find the first non-repeated character, check whether two words are anagrams, and capitalize each word of a sentence. Lastly, we will remove duplicate characters, and compress a string with run-length encoding. For each program, we will look at the idea before the code.(Note - These programs use the methods from Essential Java String MethodsClick to read tutorial: Essential Java String Methods with Examples and StringBuilderClick to read tutorial: String vs StringBuilder vs StringBuffer in Java.)
1. Reversing a string and checking for palindromes
Idea:StringBuilder.reverse() reverses a string in one call. To do it by hand, read the characters from the last to the first. A palindrome reads the same both ways; for sentences, first remove everything except letters and digits, and ignore case.
Reversing strings and checking palindromes
//Palindrome.java
public class Palindrome {
static String reverse(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
static boolean isPalindrome(String s) {
String cleaned = s.toLowerCase().replaceAll("[^a-z0-9]", "");
int left = 0, right = cleaned.length() - 1;
while (left < right) {
if (cleaned.charAt(left++) != cleaned.charAt(right--)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(reverse("JavaBrahman"));
System.out.println(new StringBuilder("JavaBrahman").reverse());
for (String s : new String[] {"Racecar", "A man, a plan, a canal: Panama", "Java"}) {
System.out.println("\"" + s + "\" palindrome? " + isPalindrome(s));
}
}
}
namharBavaJ namharBavaJ "Racecar" palindrome? true "A man, a plan, a canal: Panama" palindrome? true "Java" palindrome? false
Explanation of the code
replaceAll("[^a-z0-9]", "")removes every character which is not a lower-case letter or a digit - spaces, commas and the colon.isPalindrome()compares characters from both ends towards the middle, and stops at the first mismatch, without building a reversed copy.
2. Counting vowels, consonants and words
Idea: go through each character and classify it with theCharacter class's helper methods. For words, split on runs of whitespace - after stripping the ends, so leading spaces do not create an empty first word.
Counting vowels, consonants, digits and words
//TextStats.java
public class TextStats {
public static void main(String[] args) {
String text = " Java 25 was released in September 2025! ";
int vowels = 0, consonants = 0, digits = 0, spaces = 0;
for (char c : text.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) >= 0) vowels++;
else if (Character.isLetter(c)) consonants++;
else if (Character.isDigit(c)) digits++;
else if (Character.isWhitespace(c)) spaces++;
}
System.out.printf("vowels=%d consonants=%d digits=%d spaces=%d%n", vowels, consonants, digits, spaces);
String stripped = text.strip();
int words = stripped.isEmpty() ? 0 : stripped.split("\\s+").length;
System.out.println("words=" + words);
}
}
vowels=11 consonants=15 digits=6 spaces=10 words=7
3. Counting how often each character occurs
Idea: use a map from character to count.merge(c, 1, Integer::sum) stores 1 the first time a character is seen, and adds 1 after that. A TreeMap keeps the characters sorted.
Counting character frequency with a Map
//CharFrequency.java
import java.util.Map;
import java.util.TreeMap;
public class CharFrequency {
public static void main(String[] args) {
String word = "mississippi";
Map<Character, Integer> counts = new TreeMap<>();
for (char c : word.toCharArray()) {
counts.merge(c, 1, Integer::sum);
}
System.out.println(counts);
counts.forEach((ch, n) -> System.out.println(ch + " : " + "#".repeat(n)));
}
}
{i=4, m=1, p=2, s=4}
i : ####
m : #
p : ##
s : ####
int[26] count array indexed by c - 'a' works just as well - the same technique as the frequency count in common array programsClick to read tutorial: Common Java Array Programs with Examples.
4. First non-repeated character
Idea: count every character first, then go through the string again in its original order and return the first character whose count is 1. ALinkedHashMap would also work, as it remembers insertion order.
Finding the first non-repeated character
//FirstUnique.java
import java.util.HashMap;
import java.util.Map;
public class FirstUnique {
static Character firstUnique(String s) {
Map<Character, Integer> counts = new HashMap<>();
for (char c : s.toCharArray()) {
counts.merge(c, 1, Integer::sum);
}
for (char c : s.toCharArray()) {
if (counts.get(c) == 1) {
return c;
}
}
return null;
}
public static void main(String[] args) {
System.out.println("swiss -> " + firstUnique("swiss"));
System.out.println("javajava -> " + firstUnique("javajava"));
System.out.println("programmer-> " + firstUnique("programmer"));
}
}
swiss -> w javajava -> null programmer-> p
Character object rather than a char, so that it can return null when every character repeats.
5. Checking for anagrams
Idea: two words are anagrams if they contain exactly the same letters in a different order - "listen" and "silent". Clean both words, sort their characters, and compare the sorted results.Checking whether two words are anagrams
//Anagram.java
import java.util.Arrays;
public class Anagram {
static boolean areAnagrams(String a, String b) {
char[] x = a.toLowerCase().replaceAll("\\s", "").toCharArray();
char[] y = b.toLowerCase().replaceAll("\\s", "").toCharArray();
Arrays.sort(x);
Arrays.sort(y);
return Arrays.equals(x, y);
}
public static void main(String[] args) {
System.out.println("listen / silent : " + areAnagrams("listen", "silent"));
System.out.println("Dormitory / Dirty room : " + areAnagrams("Dormitory", "Dirty room"));
System.out.println("java / jave : " + areAnagrams("java", "jave"));
}
}
listen / silent : true Dormitory / Dirty room : true java / jave : false
6. Capitalizing each word
Idea: split the sentence into words, upper-case the first letter of each and lower-case the rest, then join the words again.Capitalizing the first letter of each word
//TitleCase.java
public class TitleCase {
static String titleCase(String sentence) {
StringBuilder sb = new StringBuilder();
for (String word : sentence.strip().split("\\s+")) {
if (sb.length() > 0) sb.append(' ');
sb.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1).toLowerCase());
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(titleCase("the quick BROWN fox"));
System.out.println(titleCase("java fundamentals series"));
}
}
The Quick Brown Fox Java Fundamentals Series
7. Removing duplicate characters
Idea: keep a set of the characters already seen, and append a character to the result only the first time it appears. ASet's add() returns false when the element is already there, which does the check and the update in one call.
Removing duplicate characters, keeping the first occurrence
//RemoveDuplicateChars.java
import java.util.HashSet;
import java.util.Set;
public class RemoveDuplicateChars {
static String removeDuplicates(String s) {
Set<Character> seen = new HashSet<>();
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (seen.add(c)) {
sb.append(c);
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(removeDuplicates("programming"));
System.out.println(removeDuplicates("bookkeeper"));
}
}
progamin bokepr
8. Compressing a string - run-length encoding
Idea: replace each run of the same character with the character and the length of the run -"aaabcc" becomes "a3b1c2". Go through the string counting repeats, and write out each run when the character changes.
Run-length encoding
//RunLength.java
public class RunLength {
static String compress(String s) {
if (s.isEmpty()) return s;
StringBuilder sb = new StringBuilder();
int run = 1;
for (int i = 1; i <= s.length(); i++) {
if (i < s.length() && s.charAt(i) == s.charAt(i - 1)) {
run++;
} else {
sb.append(s.charAt(i - 1)).append(run);
run = 1;
}
}
String compressed = sb.toString();
return compressed.length() < s.length() ? compressed : s;
}
public static void main(String[] args) {
System.out.println("aaabccddddd -> " + compress("aaabccddddd"));
System.out.println("wwwwwwwwwwb -> " + compress("wwwwwwwwwwb"));
System.out.println("abc -> " + compress("abc"));
}
}
aaabccddddd -> a3b1c2d5 wwwwwwwwwwb -> w10b1 abc -> abc
Explanation of the code
- The loop runs one step past the last character (
i <= s.length()), so that the final run is written out too. - If the "compressed" form is not shorter, as for
"abc"(which would become"a1b1c1"), the original is returned.
Summary
In this tutorial we wrote eight common string programs. We first reversed strings and checked palindromes, ignoring case and punctuation. We then counted vowels, consonants, digits and words, and counted the frequency of each character with a map. Next we found the first non-repeated character, checked anagrams by sorting characters, and capitalized each word of a sentence. Lastly, we removed duplicate characters with a set, and compressed strings with run-length encoding. This completes the strings module. In the next tutorial, we start on methods with defining, calling and returning values from methodsClick to read tutorial: Java Methods: Defining, Calling and Returning Values.Java Fundamentals Tutorials
Java Text Blocks: Multi-line Strings with ExamplesClick to read tutorial: Java Text Blocks: Multi-line Strings with Examples Java Methods: Defining, Calling and Returning ValuesClick to read tutorial: Java Methods: Defining, Calling and Returning Values Java String Basics and Why Strings Are ImmutableClick to read tutorial: Java String Basics and Why Strings Are Immutable Java String Pool: String Literals vs new String()Click to read tutorial: Java String Pool: String Literals vs new String() Java String Comparison: == vs equals() vs compareTo()Click to read tutorial: Java String Comparison: == vs equals() vs compareTo() Essential Java String Methods with ExamplesClick to read tutorial: Essential Java String Methods with Examples String vs StringBuilder vs StringBuffer in JavaClick to read tutorial: String vs StringBuilder vs StringBuffer in Java
Java Text Blocks: Multi-line Strings with ExamplesClick to read tutorial: Java Text Blocks: Multi-line Strings with Examples Java Methods: Defining, Calling and Returning ValuesClick to read tutorial: Java Methods: Defining, Calling and Returning Values Java String Basics and Why Strings Are ImmutableClick to read tutorial: Java String Basics and Why Strings Are Immutable Java String Pool: String Literals vs new String()Click to read tutorial: Java String Pool: String Literals vs new String() Java String Comparison: == vs equals() vs compareTo()Click to read tutorial: Java String Comparison: == vs equals() vs compareTo() Essential Java String Methods with ExamplesClick to read tutorial: Essential Java String Methods with Examples String vs StringBuilder vs StringBuffer in JavaClick to read tutorial: String vs StringBuilder vs StringBuffer in Java