As a beginner, practicing common string programs helps build a strong understanding of loops, conditions, arrays, and String methods. These programs are also frequently asked in coding interviews, programming tests, and academic examinations.
In this article, we will explore some of the most common String programs in Java with complete code, output, explanations, common mistakes, and best practices.
Table of Contents
Why Learn String Programs?
String programs help developers understand how text data is processed and manipulated in Java applications.- Improve Problem-Solving Skills: Many programming challenges involve string manipulation. Practicing string programs improves logical thinking and coding skills.
- Prepare for Interviews: Questions based on strings are frequently asked in technical interviews and coding assessments.
- Learn Important String Methods: String programs provide practical experience with methods such as length(), charAt(), substring(), equals(), and replace().
- Build Real-World Applications: Applications such as search engines, chat applications, form validation systems, and text editors rely heavily on string processing.
Reverse a String
Reversing a string is one of the most common string programming problems. It helps beginners understand loops and character manipulation.
// Java program to reverse a string
public class ReverseString {
public static void main(String[] args) {
String str = "Java";
String reverse = "";
for(int i = str.length() - 1; i = 0; i--) {
reverse += str.charAt(i);
}
System.out.println(reverse);
}
}
Output:
Explanation:avaJ
The loop starts from the last character and moves backward. Each character is appended to a new string, producing the reversed result.
Check Palindrome String
A palindrome is a string that remains the same when read from left to right and right to left.
// Java program to check palindrome string
public class PalindromeString {
public static void main(String[] args) {
String str = "madam";
String reverse = "";
for(int i = str.length() - 1; i = 0; i--) {
reverse += str.charAt(i);
}
if(str.equals(reverse)) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
}
Output:
Explanation:Palindrome
The program reverses the string and compares it with the original string. If both are equal, the string is a palindrome.
Count Vowels and Consonants
This program counts the number of vowels and consonants present in a string.
// Java program to count vowels and consonants
public class CountVowelsConsonants {
public static void main(String[] args) {
String str = "Java Programming";
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);
System.out.println("Consonants = " + consonants);
}
}
Output:
Explanation:Vowels = 5
Consonants = 10
The program examines each character and checks whether it is a vowel or a consonant before incrementing the appropriate counter.
Count Words in a String
This program calculates the total number of words in a sentence.
// Java program to count words in a string
public class CountWords {
public static void main(String[] args) {
String str = "Java is easy to learn";
String[] words = str.split(" ");
System.out.println("Words = " + words.length);
}
}
Output:
Explanation:Words = 5
The split() method divides the sentence into words using spaces as separators. The array length represents the total number of words.
Find String Length
This program finds the total number of characters present in a string.
// Java program to find the string length
public class StringLength {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.length());
}
}
Output:
Explanation:16
The length() method returns the total number of characters, including spaces.
Convert Uppercase to Lowercase
This program converts all uppercase letters into lowercase letters.
// Java program to convert Uppercase to Lowercase
public class LowerCaseExample {
public static void main(String[] args) {
String str = "JAVA";
System.out.println(str.toLowerCase());
}
}
Output:
Explanation:java
The toLowerCase() method converts each uppercase letter into its lowercase equivalent.
Convert Lowercase to Uppercase
This program converts all lowercase letters into uppercase letters.
// Java program to convert Lowercase to Uppercase
public class UpperCaseExample {
public static void main(String[] args) {
String str = "java";
System.out.println(str.toUpperCase());
}
}
Output:
Explanation:JAVA
The toUpperCase() method converts all lowercase letters into uppercase letters.
Remove White Spaces
This program removes all spaces from a string.
// Java program to remove whitespaces
public class RemoveSpaces {
public static void main(String[] args) {
String str = "Java Programming Language";
str = str.replace(" ", "");
System.out.println(str);
}
}
Output:
Explanation:JavaProgrammingLanguage
The replace() method replaces every space character with an empty string.
Check Anagram Strings
Two strings are called anagrams if they contain the same characters in different orders.
// Java program to check anagram strings
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
System.out.println(Arrays.equals(arr1, arr2));
}
}
Output:
Explanation:true
Both strings are converted into character arrays and sorted. If the sorted arrays are identical, the strings are anagrams.
Find Duplicate Characters
This program identifies duplicate characters present in a string.
// Java program to find duplicate characters
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
for(int i = 0; i str.length(); i++) {
int count = 1;
for(int j = i + 1; j str.length(); j++) {
if(str.charAt(i) == str.charAt(j)) {
count++;
}
}
if(count 1) {
System.out.println(str.charAt(i));
}
}
}
}
Output:
Explanation:r
g
m
The nested loops compare characters and identify those appearing more than once.
Common Mistakes
1. Using == Instead of equals(): The == operator compares object references rather than actual string content. Use equals() when comparing string values.Incorrect:
2. Ignoring String Immutability: String methods return new objects. If the returned value is not stored, the modification is lost.String str1 = "Java";
String str2 = new String("Java");
System.out.println(str1 == str2);
Incorrect:
3. Not Handling Case Differences: The equals() method is case-sensitive. Use equalsIgnoreCase() when case differences should be ignored.String str = "java";
str.toUpperCase();
Incorrect:
4. Using String Concatenation Inside Large Loops:Repeated concatenation creates many temporary String objects and can reduce performance. StringBuilder is a better alternative.String str1 = "JAVA";
String str2 = "java";
System.out.println(str1.equals(str2));
Incorrect:
String result = "";
for(int i = 0; i 1000; i++) {
result += i;
}
Best Practices
- Use StringBuilder for Frequent Modifications: StringBuilder provides better performance when strings are modified repeatedly.
- Use Built-in String Methods: Methods such as split(), replace(), contains(), and substring() simplify string manipulation tasks.
- Validate User Input: Always validate strings before processing them to avoid unexpected errors.
- Handle Case Sensitivity Carefully: Choose between equals() and equalsIgnoreCase() based on the requirement.
- Write Modular Programs: Create separate methods for string operations to improve readability and maintainability.
Conclusion
String programming is an important part of Java development. Common string programs, such as reversing strings, checking palindromes, counting words, finding duplicates, and checking anagrams, help developers strengthen their understanding of string manipulation techniques.Mastering these programs improves problem-solving skills, prepares developers for coding interviews, and provides a strong foundation for building real-world Java applications.
Frequently Asked Questions
1. Why are string programs important in Java?2. Which string program is most commonly asked in interviews?String programs help developers understand text processing, manipulation, and problem-solving techniques used in real-world applications.
3. What is an anagram string?Reverse string and palindrome string programs are among the most frequently asked interview questions.
4. Which class is better for frequent string modifications?Two strings are anagrams if they contain the same characters arranged in a different order.
5. Which String method is most commonly used?StringBuilder is preferred because it avoids unnecessary object creation.
Methods such as length(), charAt(), equals(), substring(), and split() are commonly used in Java applications.
0 Comments