CACS204 Object Oriented Programming in Java

Object Oriented Programming in JavaUnit 128 min read

String Handling in Java: Methods, Manipulation & Real-World Use

Unit 12 of Object Oriented Programming in Java covers Java's String class, its immutable nature, core methods (substring, concat, replace, split, etc.), regex support, and practical applications in text processing, validation, and parsing. Includes real-world examples from eSewa, Ncell, and Kathmandu traffic systems.

TAKEAWAYS:

  • Java String is immutable, meaning every operation creates a new object (memory efficiency trade-off).
  • Core methods like substring(), split(), and replace() enable powerful text manipulation without loops.
  • Regex (Pattern/Matcher) unlocks advanced pattern matching (e.g., email validation, phone number parsing).
  • StringBuilder/StringBuffer bypass immutability for high-performance concatenation (e.g., log generation).
  • Real-world uses include eSewa’s transaction IDs (random string generation), Ncell’s SMS parsing, and Kathmandu traffic route validation.
  • Exam focus: Method examples, regex patterns, and performance comparisons (e.g., + vs. StringBuilder).

1. The String Class: Immutable by Design

Java’s String is a sequence of Unicode characters stored in a char[] array. Its immutability ensures thread safety and optimizes memory via string pooling (interned strings).

Why Immutability?

graph LR
    A["Immutable String"] --> B["Thread-safe"]
    A --> C["String Pool Optimization"]
    A --> D["HashCode Caching"]
  • Thread-safe: No risk of corruption in multithreaded apps (e.g., Ncell’s SMS parser).
  • String Pool: Literals ("hello") reuse memory; intern() forces pooling.
  • HashCode Caching: Used in HashMap/HashSet keys (e.g., eSewa’s user lookup).

Creating Strings

String s1 = "hello";       // Literal (pool)
String s2 = new String("hi"); // Heap
String s3 = s1.intern();   // Forces pooling

Visual: String Pool vs. Heap



2. Core String Methods (Exam Focus)

A. Manipulation Methods

Method Example Use Case
concat() "a".concat("b") → "ab" Building paths (e.g., Daraz’s order URLs)
substring() "hello".substring(1) → "ello" Extracting tokens (e.g., Ncell’s phone number parsing)
replace() "abc".replace('a', 'x') → "xbc" Sanitizing input (e.g., eSewa’s transaction IDs)
trim() " hi ".trim() → "hi" Cleaning user input (e.g., Khalti’s form data)
toUpperCase() "Hi".toUpperCase() → "HI" Case-insensitive comparisons

B. Searching & Validation

Method Example Use Case
contains() "hello".contains("ell") → true Checking substrings (e.g., NEPSE’s stock symbol validation)
startsWith() "file.txt".startsWith("file") → true File extensions (e.g., NTC’s log parsers)
equals() "a".equals("A") → false Never use == for strings!
isEmpty() "".isEmpty() → true Validating user input

Worked Example: eSewa Transaction ID Validation

String txnId = "TXN12345";
boolean isValid = txnId.matches("TXN\\d{5}"); // Regex check

Regex Breakdown:

  • TXN → Literal prefix
  • \\d{5} → Exactly 5 digits Visual: Regex Matching


3. Splitting & Joining Strings

A. split() with Regex

String csv = "apple,banana,cherry";
String[] items = csv.split(","); // ["apple", "banana", "cherry"]

Real-World Use: Parsing Khalti’s transaction logs (CSV format).

B. join() (Java 8+)

String result = String.join("-", items); // "apple-banana-cherry"

Use Case: Generating Daraz’s order reference IDs.

Visual: Splitting a CSV String



4. StringBuilder vs. StringBuffer

Feature StringBuilder StringBuffer
Thread-safe ❌ No ✅ Yes (synchronized)
Performance Faster (no locking) Slower (overhead)
Use Case Single-threaded apps Multi-threaded apps (e.g., Ncell’s concurrent log builder)

Example: Building a Large String

StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("World"); // "Hello World"

Visual: StringBuilder Growth



5. Regex in Java: Pattern and Matcher

Key Classes

  • Pattern: Compiles regex (e.g., Pattern.compile("\\d{5}")).
  • Matcher: Applies pattern to input (e.g., matcher.find()).

Example: Validating Ncell Phone Numbers

String phone = "9800123456";
Pattern pattern = Pattern.compile("98\\d{8}");
Matcher matcher = pattern.matcher(phone);
boolean isValid = matcher.matches(); // true

Visual: Regex Matching Steps



6. Practical Applications

A. eSewa: Transaction ID Generation

String generateTxnId() {
    return "TXN" + (int)(Math.random() * 100000);
}

Why Strings?

  • Immutable → Safe for concurrent access.
  • Easy concatenation with StringBuilder.

B. Ncell: SMS Parsing

String sms = "Your balance is 500. Refill at *123#";
String[] parts = sms.split(" ");
String balance = parts[3]; // "500"

Visual: SMS Parsing Flow

```mermaid
flowchart TD
    A["Raw SMS"] --> B["Split by Space"]
    B --> C["Extract Balance"]
    C --> D["Display Alert"]

C. Kathmandu Traffic: Route Validation

String route = "RingRoad->Thapathali";
boolean isValid = route.matches(".*->.*"); // Checks for "->"

Use Case: Ensuring route strings follow a standard format.


7. Performance Pitfalls

A. Inefficient Concatenation

// Bad: Creates 3 String objects!
String bad = "a" + "b" + "c";

// Good: Uses StringBuilder
StringBuilder sb = new StringBuilder();
sb.append("a").append("b").append("c");
String good = sb.toString();

Visual: String Concatenation Overhead


B. + vs. StringBuilder Benchmark

Operation + (30 ops) StringBuilder (1 op)
Time (ms) 120 1
Memory Allocations 30 1

8. Exam Tip: Common Pitfalls

  1. == vs. equals():
    String a = "hello";
    String b = new String("hello");
    System.out.println(a == b); // false (different objects)
    System.out.println(a.equals(b)); // true (same content)
    
  2. Regex Escaping:
    // Wrong: \d matches a literal 'd'
    // Correct: \\d matches digits
    
  3. Immutability:
    • s1.concat("!") does not modify s1; it returns a new String.
  4. String Pool:
    • "hello" and new String("hello").intern() refer to the same object.

Visual: == vs. equals()



9. Full-Exam Question Walkthrough

Question: Write a program to check if a user’s password meets these rules:

  • At least 8 chars.
  • Contains 1 digit.
  • Contains 1 uppercase letter.

Solution:

import java.util.regex.*;

public class PasswordValidator {
    public static boolean isValid(String password) {
        return password.length() >= 8 &&
               password.matches(".*\\d.*") &&
               password.matches(".*[A-Z].*");
    }

    public static void main(String[] args) {
        System.out.println(isValid("Weak1")); // false (too short)
        System.out.println(isValid("Strong1")); // true
    }
}

Visual: Password Validation Flow

```mermaid
flowchart TD
    A["Input Password"] --> B["Length ≥8?"]
    B -->|No| C["Reject"]
    B -->|Yes| D["Contains Digit?"]
    D -->|No| C
    D -->|Yes| E["Contains Uppercase?"]
    E -->|No| C
    E -->|Yes| F["Accept"]

Key Takeaway for Exams:

  • Always use equals() for string comparison.
  • Regex is your friend: Master .*, \\d, [A-Z], and ^/$.
  • StringBuilder for loops: Avoid + in concatenation loops.
  • Real-world tie-ins: Relate methods to eSewa, Ncell, or Khalti scenarios.

Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 12.

Discussion

Loading…