Strings in Java
Subject: Data Structures and Algorithms · Language: Java · Level: beginner · 6 min read
Understand String, charAt, length, StringBuilder, traversal, palindrome, and text-based DSA problems.
A string is a sequence of characters. Names, passwords, email IDs, sentences, roll numbers, and codes are all examples of strings. Java provides a built-in `String` class, so string handling is easier than languages where characters must be managed manually. Still, in DSA, string problems require careful thinking about indexes, comparison, character frequency, and how text changes inside loops.
String Basics
```java
String name = "PrepCampus";
```
Here, `name` stores a sequence of characters. The first character is `P`, the second character is `r`, and the remaining characters follow in order. `name.length()` gives the number of characters in the string. `name.charAt(i)` gives the character present at index `i`. These two methods are used in almost every beginner string problem.
String Indexing
String indexing starts from 0. For a string of length `n`, the last valid index is `n - 1`. For example, in `Java`, index `0` stores `J`, index `1` stores `a`, index `2` stores `v`, and index `3` stores `a`.
If you try to access an index outside this range, Java throws `StringIndexOutOfBoundsException`.
String Is Immutable
In Java, `String` is immutable. That means once a string is created, its content cannot be changed directly. When you write `str = str + "a"`, Java does not modify the old string. It creates a new string and makes `str` refer to the new value.
This is fine for small programs, but repeated string changes inside loops can become slow.
StringBuilder
For repeated changes, use `StringBuilder`. It allows efficient modification of text because it can update the same object instead of creating many new strings again and again. `StringBuilder` is commonly used in reverse-string problems, pattern-building problems, and output-building problems where text changes many times.
```java
StringBuilder sb = new StringBuilder();
sb.append("Java");
sb.append(" DSA");
System.out.println(sb.toString());
```
Important String Methods
- `length()` returns the number of characters
- `charAt(index)` returns the character at a given index
- `substring(start, end)` returns part of a string
- `equals()` compares string values
- `equalsIgnoreCase()` compares values without checking letter case
- `toLowerCase()` converts letters to lowercase
- `toUpperCase()` converts letters to uppercase
- `trim()` removes extra spaces from the beginning and end
Use `equals()` for comparing string values. Do not use `==` for normal string comparison because `==` checks references, not actual text value.
Traversing a String
Traversing means visiting each character one by one. Most string problems use a loop from `0` to `str.length() - 1`.
```java
String str = "Java";
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
```
This pattern is used in vowel counting, frequency counting, palindrome checking, and character searching.
Common String Patterns
- Count vowels, consonants, digits, and spaces
- Reverse a string using `StringBuilder` or two-pointer logic
- Check whether a string is palindrome
- Compare two strings using `equals()`
- Count frequency of characters using an array or map
- Find the first non-repeating character
- Build a new string after removing or replacing characters
Palindrome String
A palindrome string reads the same from left to right and right to left. Examples are `level`, `madam`, and `racecar`. To check a palindrome, compare the first character with the last character, the second character with the second-last character, and continue moving toward the middle.
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); System.out.print("Enter a word: ");
String word = sc.next(); int left = 0;
int right = word.length() - 1;
boolean isPalindrome = true; while (left < right) {
if (word.charAt(left) != word.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
if (isPalindrome) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
}
```
Character Frequency
Frequency means how many times something appears. In string problems, character frequency is used to count letters. For lowercase English letters, an integer array of size 26 is commonly used.
```java
int[] freq = new int[26];
String str = "banana";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
freq[ch - 'a']++;
}
``` Here, `ch - 'a'` converts a lowercase character into an index. For example, `a` becomes 0, `b` becomes 1, and `z` becomes 25.
Strings in DSA
String problems are common in placement preparation because they test both logic and careful indexing. A small index mistake can change the answer or cause `StringIndexOutOfBoundsException`. When solving a string problem, first decide whether you need to read characters, compare two strings, build a new string, or count frequency. This decision helps you choose between `String`, `StringBuilder`, arrays, and maps.
Practice Question
Take a string as input and print the number of vowels, consonants, digits, and spaces.