Practice: String Processing
This lesson is the hands-on practice for Phase 2, consolidating string processing skills through 5 projects.
Project 1: String Reversal
Skills used: StringBuilder, String.toCharArray().
Requirements
Write a method to reverse a string.
Implementation
public class StringReverse {
// Method 1: StringBuilder
public static String reverse1(String str) {
if (str == null) return null;
return new StringBuilder(str).reverse().toString();
}
// Method 2: Character array
public static String reverse2(String str) {
if (str == null) return null;
char[] chars = str.toCharArray();
int left = 0, right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
// Method 3: Recursion
public static String reverse3(String str) {
if (str == null || str.length() <= 1) {
return str;
}
return reverse3(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
String s = "Hello, World!";
System.out.println("Original: " + s);
System.out.println("Reverse 1: " + reverse1(s));
System.out.println("Reverse 2: " + reverse2(s));
System.out.println("Reverse 3: " + reverse3(s));
}
}
Output:
Original: Hello, World!
Reverse 1: !dlroW ,olleH
Reverse 2: !dlroW ,olleH
Reverse 3: !dlroW ,olleH
Project 2: Word Count
Skills used: String.split(), for-each loop.
Requirements
Count the number of words in a string.
Implementation
public class WordCount {
public static int countWords(String str) {
if (str == null || str.trim().isEmpty()) {
return 0;
}
// Split by whitespace, trim removes leading/trailing spaces
String[] words = str.trim().split("\\s+");
return words.length;
}
public static void main(String[] args) {
System.out.println(countWords("Hello World")); // 2
System.out.println(countWords(" Hello World ")); // 2
System.out.println(countWords("Java is awesome")); // 3
System.out.println(countWords("")); // 0
System.out.println(countWords(null)); // 0
}
}
Project 3: Palindrome Detection
Skills used: StringBuilder, two pointers.
Requirements
Determine if a string is a palindrome (reads the same forwards and backwards).
Implementation
public class Palindrome {
// Method 1: StringBuilder reverse
public static boolean isPalindrome1(String str) {
if (str == null) return false;
String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}
// Method 2: Two pointers
public static boolean isPalindrome2(String str) {
if (str == null) return false;
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
// Ignore case and non-alphanumeric characters
public static boolean isPalindromeIgnore(String str) {
if (str == null) return false;
String cleaned = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
return isPalindrome2(cleaned);
}
public static void main(String[] args) {
System.out.println(isPalindrome1("racecar")); // true
System.out.println(isPalindrome1("hello")); // false
System.out.println(isPalindromeIgnore("A man, a plan, a canal: Panama")); // true
}
}
Project 4: Date Calculation
Skills used: LocalDate, ChronoUnit, Period.
Requirements
Calculate the difference in days, years, months, and days between two dates.
Implementation
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class DateCalculator {
// Calculate days between
public static long daysBetween(LocalDate start, LocalDate end) {
return ChronoUnit.DAYS.between(start, end);
}
// Calculate years, months, days between
public static Period periodBetween(LocalDate start, LocalDate end) {
return Period.between(start, end);
}
// Check leap year
public static boolean isLeapYear(int year) {
return LocalDate.of(year, 1, 1).isLeapYear();
}
// Get days in month
public static int daysInMonth(int year, int month) {
return LocalDate.of(year, month, 1).lengthOfMonth();
}
public static void main(String[] args) {
LocalDate start = LocalDate.of(2026, 1, 1);
LocalDate end = LocalDate.of(2026, 12, 31);
System.out.println("Days between: " + daysBetween(start, end)); // 364
Period period = periodBetween(start, end);
System.out.println("Period: " + period); // P11M30D
System.out.println("2026 is leap year: " + isLeapYear(2026)); // false
System.out.println("2024 is leap year: " + isLeapYear(2024)); // true
System.out.println("Days in Feb 2026: " + daysInMonth(2026, 2)); // 28
}
}
Project 5: String Encryption
Skills used: charAt(), StringBuilder, ASCII arithmetic.
Requirements
Implement a simple Caesar cipher (shift each letter by 3 positions).
Implementation
public class CaesarCipher {
public static String encrypt(String text, int shift) {
StringBuilder result = new StringBuilder();
for (char c : text.toCharArray()) {
if (Character.isLetter(c)) {
char base = Character.isUpperCase(c) ? 'A' : 'a';
// Encrypt: (char - base + shift) % 26 + base
char encrypted = (char) ((c - base + shift) % 26 + base);
result.append(encrypted);
} else {
result.append(c);
}
}
return result.toString();
}
public static String decrypt(String text, int shift) {
return encrypt(text, 26 - shift);
}
public static void main(String[] args) {
String original = "Hello, World!";
int shift = 3;
String encrypted = encrypt(original, shift);
String decrypted = decrypt(encrypted, shift);
System.out.println("Original: " + original);
System.out.println("Encrypted: " + encrypted); // Khoor, Zruog!
System.out.println("Decrypted: " + decrypted); // Hello, World!
}
}
Additional Practice
Exercise 1: Character Frequency
import java.util.HashMap;
import java.util.Map;
public class CharFrequency {
public static Map<Character, Integer> frequency(String str) {
Map<Character, Integer> map = new HashMap<>();
for (char c : str.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
return map;
}
public static void main(String[] args) {
String s = "hello world";
Map<Character, Integer> freq = frequency(s);
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
System.out.println("'" + entry.getKey() + "' : " + entry.getValue());
}
}
}
Exercise 2: Camel Case Conversion
public class CamelCase {
// Underscore to camelCase
public static String toCamelCase(String str) {
StringBuilder result = new StringBuilder();
boolean capitalizeNext = false;
for (char c : str.toCharArray()) {
if (c == '_') {
capitalizeNext = true;
} else {
if (capitalizeNext) {
result.append(Character.toUpperCase(c));
capitalizeNext = false;
} else {
result.append(c);
}
}
}
return result.toString();
}
// camelCase to underscore
public static String toSnakeCase(String str) {
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) {
result.append('_');
result.append(Character.toLowerCase(c));
} else {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(toCamelCase("hello_world")); // helloWorld
System.out.println(toSnakeCase("helloWorld")); // hello_world
}
}
❓ Frequently Asked Questions
📖 Summary
- String reversal: StringBuilder.reverse() or two pointers
- Word count: split("\s+") then count
- Palindrome: reverse comparison or two pointers
- Date calculation: LocalDate + ChronoUnit/Period
- Caesar cipher: ASCII arithmetic
📝 Exercises
- String compression: Compress "aaabbbcc" to "a3b3c2"
- Email validation: Determine if a string is a valid email format
- Date utility class: Write a DateUtils class with methods for age calculation, days between, formatting, etc.
Next Lesson
In the next lesson, we'll move to Phase 3 and learn about Classes and Objects — entering the world of object-oriented programming.



