Reverse a String
public class ReverseString {
public static void main(String[] args) {
String original = "Testing";
String reversed = "";
for (int i = original.length() - 1; i >= 0; i--) {
reversed = reversed + original.charAt(i);
}
System.out.println("Reversed String: " + reversed);
}
}
Logic
Traverse the string from the last character to the first and append every character to build the reversed string.
Using StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = original.length() - 1; i >= 0; i--) {
sb.append(original.charAt(i));
}
// or
new StringBuilder(original).reverse().toString();
StringBuilder is preferred because it avoids creating multiple intermediate String objects.
Palindrome Check
A palindrome string reads the same in both forward and reverse directions.
Logic
- Reverse the string.
- Compare it with the original string using:
.equals()
If both strings are equal, the string is a palindrome.
Another approach uses two pointers:
- Compare the first and last characters.
- Move both pointers toward the center.
- Stop immediately if a mismatch is found.
Time Complexity: O(n)
Compare Two Strings
Use the appropriate comparison method based on the requirement.
Content Comparison
.equals()
Case-Insensitive Comparison
.equalsIgnoreCase()
Lexicographical Comparison
.compareTo()
Avoid using:
==
because it compares object references rather than string content.
Count Vowels & Consonants
public class CountVowelsConsonants {
public static void main(String[] args) {
String str = "Automation";
int vowels = 0;
int consonants = 0;
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels +
", Consonants: " + consonants);
}
}
Logic
- Convert the string to lowercase.
- Process only alphabetic characters.
- Increment the vowel count for vowels.
- Increment the consonant count for remaining alphabetic characters.
Character Frequency & Duplicate Characters
Duplicate Characters
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
int count = 1;
if (chars[i] == '0')
continue;
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
count++;
chars[j] = '0';
}
}
if (count > 1)
System.out.println(chars[i] + " -> " + count);
}
Logic
- Convert the string into a character array.
- Count repeated characters.
- Mark processed characters so they are not counted again.
- Print only characters that appear more than once.
Optimized Approach
Use a HashMap.
map.put(ch, map.getOrDefault(ch, 0) + 1);
This approach performs frequency counting in a single traversal.
Remove Duplicate Characters
Use a LinkedHashSet<Character> to preserve insertion order while eliminating duplicate characters.
First Non-Repeated Character
Logic
- Count the frequency of every character.
- Traverse the string again.
- Return the first character whose frequency equals
1.
A LinkedHashMap preserves insertion order while counting frequencies.
Time Complexity: O(n)
Only Digits / Only Alphabets
Only Digits
Use:
Character.isDigit(ch)
or
str.matches("[0-9]+")
Only Alphabets
Use:
Character.isLetter(ch)
or
str.matches("[a-zA-Z]+")
Swap Characters
Since String objects are immutable:
- Convert the string into a character array.
- Swap the required characters.
- Build the string again.
Frequently Asked Questions
How do you reverse a string in Java?
Traverse the string from the last index to the first or use:
new StringBuilder(str).reverse().toString();
How do you check whether a string is a palindrome?
Reverse the string and compare it with the original using:
.equals()
Alternatively, compare characters using the two-pointer approach.
Why should .equals() be used instead of ==?
==compares object references..equals()compares string content..equalsIgnoreCase()performs case-insensitive comparison.
How do you find the first non-repeated character?
Count character frequencies using a LinkedHashMap and return the first character whose frequency equals 1.
How do you count character frequency efficiently?
Use a HashMap with:
map.put(ch, map.getOrDefault(ch, 0) + 1);
This performs frequency counting in linear time.