Follow Us
Select Medium / माध्यम चुनें:
Eng (English) Hindi (हिन्दी)
ICSE • Class X • Information Technology • Ch 8
Estimated Time: 45 Mins
Study Progress: In Progress

String handling

Exhaustive masterclass on String Handling and Manipulation in Java for ICSE Class 10. Covers String immutability, String Constant Pool (SCP) vs Heap, content vs reference equality (== vs equals), complete library method specifications, Pig Latin, Palindrome, sentence tokenization, alphabetical name sorting, and board programming solutions.

Why This Chapter Matters

Exhaustive masterclass on String Handling and Manipulation in Java for ICSE Class 10. Covers String immutability, String Constant Pool (SCP) vs Heap, content vs reference equality (== vs equals), complete library method specifications, Pig Latin, Palindrome, sentence tokenization, alphabetical name sorting, and board programming solutions.

Chapter Roadmap & Progression

1 1. String Immutability & The String...
2 2. Equality in Strings: '==' vs '.e...
3 3. Essential String Extraction Meth...
4 4. Search, Case Transformation & Wh...
5 5. Mutable String Alternatives: Str...
6 6. Classic ICSE Algorithm 1: Palind...
7 7. Complete ICSE Board Program: Pig...
8 8. Complete ICSE Board Program: Alp...

Complete Concept Guide (100% Curriculum Coverage)

1. String Immutability & The String Constant Pool (SCP) Architecture

String Immutability
The Architectural Immutability of Strings:

In Java, strings are represented by the java.lang.String class. Unlike primitive characters, a String object is immutable—its character array cannot be modified, resized, or overwritten after creation. Any method that appears to modify a String (such as concat(), replace(), or toUpperCase()) does not alter the original instance; it allocates and returns a completely new String object on the Heap.

String Constant Pool (SCP) vs Standard Heap:

To conserve RAM, the JVM manages a specialized cache in Heap memory called the String Constant Pool (SCP):

  • Literal Creation (String s1 = "INDIA";): The JVM checks the SCP. If "INDIA" already exists, no new memory is allocated; s1 simply receives the reference to the existing pooled instance.
  • Keyword Creation (String s2 = new String("INDIA");): The new operator bypasses the SCP check and forcibly instantiates an independent, distinct object in regular Heap memory.

2. Equality in Strings: '==' vs '.equals()' vs '.compareTo()'

String Comparison
The Three Modes of String Comparison:
Comparison Operator / MethodComparison CriterionReturn Data TypeExample & Output
== Operator Compares memory addresses (whether two references point to the exact same Heap object). boolean s1 == s2 (true for pooled literals; false for new strings)
boolean equals(Object obj) Compares actual character sequence case-sensitively. boolean "Apple".equals("Apple") // true
"Apple".equals("apple") // false
boolean equalsIgnoreCase(String s) Compares character sequence ignoring uppercase/lowercase distinctions. boolean "Apple".equalsIgnoreCase("apple") // true
int compareTo(String s) Performs lexicographical comparison (ASCII subtraction of first mismatched characters). int ($<0, 0, >0$) "A".compareTo("B") // returns -1
"C".compareTo("A") // returns +2

3. Essential String Extraction Methods: charAt() & substring()

Extraction Methods
1. charAt(int index):

Returns the character at the specified index ($0$ to $\text{length} - 1$).

String s = "COMPUTER";
char ch = s.charAt(3); // Returns 'P' (indices: 0:C, 1:O, 2:M, 3:P)
2. substring(int beginIndex):

Returns a new string containing characters from beginIndex to the end of the string.

String s = "UNDERSTAND";
String sub = s.substring(5); // Returns "STAND" (indices 5 through 9)
3. substring(int beginIndex, int endIndex):

Extracts characters starting at beginIndex (inclusive) up to endIndex - 1 (exclusive). The character at endIndex is NEVER included!

String s = "WONDERFUL";
String sub = s.substring(0, 6); // Returns "WONDER" (indices 0, 1, 2, 3, 4, 5)
Formula for Substring Length: The length of str.substring(a, b) is always exactly $b - a$.

4. Search, Case Transformation & Whitespace Trimming Methods

Search & Utility Methods
Standard Utility Operations:
Method SignatureFunctionalityExample CallReturned Output
int indexOf(char ch)
int indexOf(String str)
Returns the index of the first occurrence of character/substring, or -1 if not found. "MALAYALAM".indexOf('A') 1
int lastIndexOf(char ch) Returns the index of the last occurrence of character, or -1. "MALAYALAM".lastIndexOf('A') 7
String toLowerCase() Converts all characters to lowercase. "ICSE 2026".toLowerCase() "icse 2026"
String toUpperCase() Converts all characters to uppercase. "java".toUpperCase() "JAVA"
String trim() Strips leading and trailing spaces; internal spaces preserved. " Target Exams ".trim() "Target Exams"
String replace(char old, char new) Replaces all occurrences of old with new. "BANANA".replace('A', 'O') "BONONO"
boolean startsWith(String p) Checks if string starts with prefix p. "PREVIEW".startsWith("PRE") true
boolean endsWith(String s) Checks if string ends with suffix s. "STUDENT.java".endsWith(".java") true

5. Mutable String Alternatives: StringBuffer & StringBuilder

Mutable Alternatives
Why StringBuffer / StringBuilder?

Because String is immutable, repeated concatenation inside loops creates hundreds of discarded intermediate objects on the Heap, degrading performance. To solve this, Java provides two mutable companion classes:

  • StringBuffer: Thread-safe, synchronized, thread-safe for multi-threaded environments.
  • StringBuilder: Non-synchronized, faster performance, ideal for single-threaded algorithms.
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming"); // Mutates in-place!
sb.reverse();              // Reverses character order directly!
System.out.println(sb);    // Prints reversed string without creating intermediate objects

6. Classic ICSE Algorithm 1: Palindrome & Special Word Checkers

Board Algorithm 1
Palindrome Word vs Special Word:
  • Palindrome Word: Reads the same backward as forward (e.g., MADAM, NITIN, RACECAR).
  • Special Word: Begins and ends with the exact same letter (e.g., WINDOW begins with 'W' and ends with 'W'; EXIST begins and ends with 'E').
// Special Word & Palindrome Evaluation
String w = "MADAM";
w = w.toUpperCase();

// 1. Special Word Check:
boolean isSpecial = (w.charAt(0) == w.charAt(w.length() - 1));

// 2. Palindrome Check:
String rev = "";
for (int i = w.length() - 1; i >= 0; i--) {
    rev += w.charAt(i);
}
boolean isPalindrome = w.equals(rev);

System.out.println("Special Word   : " + isSpecial);
System.out.println("Palindrome Word: " + isPalindrome);

7. Complete ICSE Board Program: Pig Latin Word Translator

Board Program Solution
Model Program 1: Pig Latin Translation Algorithm

Pig Latin Definition: A word is converted to Pig Latin by locating the first vowel in the word ($A, E, I, O, U$). All characters from that vowel to the end of the word form the beginning of the Pig Latin word, followed by the consonants preceding the vowel, and finally suffixed with "AY". If no vowel is found, "AY" is simply appended at the end.

Examples: "LONDON" → "ONDONLAY"; "TROUBLE" → "OUBLETRAY"; "EAT" → "EATAY".

import java.util.Scanner;

public class PigLatinTranslator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String word = sc.next().toUpperCase();

        int vowelIndex = -1;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
                vowelIndex = i;
                break;
            }
        }

        String pigLatin;
        if (vowelIndex != -1) {
            pigLatin = word.substring(vowelIndex) + word.substring(0, vowelIndex) + "AY";
        } else {
            pigLatin = word + "AY";
        }

        System.out.println("Original Word : " + word);
        System.out.println("Pig Latin Word: " + pigLatin);
    }
}

8. Complete ICSE Board Program: Alphabetical Name Sorting using compareTo()

Board Program Solution
Model Program 2: Bubble Sort on Array of Names using compareTo()
import java.util.Scanner;

public class SortNamesLexicographical {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] names = new String[5];

        System.out.println("Enter 5 names:");
        for (int i = 0; i < names.length; i++) {
            System.out.print("Name " + (i + 1) + ": ");
            names[i] = in.nextLine().trim();
        }

        // Bubble Sort using compareTo()
        for (int i = 0; i < names.length - 1; i++) {
            for (int j = 0; j < names.length - 1 - i; j++) {
                // If names[j] comes alphabetically after names[j+1]:
                if (names[j].compareTo(names[j + 1]) > 0) {
                    String temp = names[j];
                    names[j] = names[j + 1];
                    names[j + 1] = temp;
                }
            }
        }

        System.out.println("
Names in Alphabetical (Lexicographical) Order:");
        for (String n : names) {
            System.out.println(n);
        }
    }
}

Common Misconceptions & Examiner Traps

Common Misconception

Using '==' to compare string text content instead of .equals()

Scientific Reality & Correction

Always use .equals() for text comparison. '==' compares memory addresses and returns false for new String() objects even with identical text.

Common Misconception

Believing endIndex in substring(beginIndex, endIndex) is inclusive

Scientific Reality & Correction

endIndex is EXCLUSIVE. str.substring(1, 4) extracts characters at indices 1, 2, and 3 only (length = 4 - 1 = 3).

Common Misconception

Expecting str.toUpperCase() or trim() to modify the string in-place without reassignment

Scientific Reality & Correction

Strings are immutable. You must assign the result back: 'str = str.toUpperCase();'.

Common Misconception

Accessing index str.length() with charAt()

Scientific Reality & Correction

Valid indices range from 0 to str.length() - 1. Calling str.charAt(str.length()) throws a StringIndexOutOfBoundsException.

Architectural Blueprint : String handling

ICSE Class 10 Java : String Immutability, Memory Pools & Core Methods Stack References String s1 = "ICSE"; String s2 = "ICSE"; Both s1 & s2 point to same SCP entry! String s3 = new String("ICSE"); s3 points to independent Heap block! s1 == s2 : true | s1 == s3 : false Heap Memory Area String Constant Pool (SCP) "ICSE" [Addr: 0x1A] Unique literals reused across threads Regular Heap Allocation "ICSE" [Addr: 0x9F] Created via new operator High-Frequency ICSE String Methods Reference Matrix • Extraction: charAt(idx), substring(start), substring(start, end) [end is exclusive!]. • Search & Modify: indexOf(ch), lastIndexOf(ch), trim(), replace(old, new), toLowerCase(), toUpperCase(). • Comparison: equals(str) [exact], equalsIgnoreCase(str), compareTo(str) [lexicographical difference].

Chapter Summary & 10 Key Takeaways

Takeaway 1
In Java, String objects are immutable: once constructed in memory, their character contents can never be modified or resized.
Takeaway 2
String literals (e.g. `"KOLKATA"`) are stored in a specialized memory zone within the Heap called the String Constant Pool (SCP) to maximize memory efficiency through reuse.
Takeaway 3
The `==` operator compares object memory addresses (reference identity), whereas `.equals()` compares the actual character-by-character text content.
Takeaway 4
`charAt(int index)` returns the `char` at the specified zero-based index; invalid indices throw a runtime `StringIndexOutOfBoundsException`.
Takeaway 5
`substring(int start, int end)` returns a sub-sequence beginning at index `start` (inclusive) and ending at index `end - 1` (exclusive).
Takeaway 6
`compareTo(String anotherString)` performs lexicographical (ASCII) comparison: returns 0 if equal, negative if invoking string precedes, positive if it succeeds.
Takeaway 7
`indexOf(char/str)` returns the first occurrence index (or -1 if not found); `lastIndexOf()` returns the final occurrence index.
Takeaway 8
The `trim()` method eliminates all leading and trailing whitespace characters, leaving interior whitespace undisturbed.
Takeaway 9
String concatenation using `+` does not modify the original string; it dynamically instantiates a brand-new String object in Heap memory.
Takeaway 10
For intensive string mutations (such as inside tight loops), mutable classes `StringBuffer` (thread-safe) or `StringBuilder` (high performance) are preferred.

Check Your Understanding (Diagnostic Practice Questions)

Diagnostic questions testing core conceptual clarity. Answers are hidden initially — solve each problem first, then click to reveal the step-by-step verified solution.

1
What is meant by String Immutability in Java? How does memory behave during string concatenation?
Reveal Answer & Explanation
Answer: String immutability means that once a java.lang.String object is instantiated in Heap memory, its internal character sequence and size can never be modified. When string concatenation (e.g., 'str = str + " Java";') is performed, the original String object is NOT modified; instead, the Java Virtual Machine dynamically allocates a brand-new String object on the Heap containing the concatenated text and points the reference variable to this new address, leaving the old string eligible for garbage collection if unreferenced.
2
Differentiate between the '==' operator and the '.equals()' method when comparing strings.
Reveal Answer & Explanation
Answer: The '==' operator performs reference (address) equality comparison: it checks whether two reference variables point to the exact same physical memory location in the Heap or String Constant Pool (e.g., 's1 == s2' is false if one is pooled and one was created via 'new'). The '.equals()' method performs semantic content comparison: it compares the actual character sequences of the two strings case-sensitively and returns true if they contain identical characters in identical order, regardless of their memory locations.
3
Explain the return values of the compareTo() method with examples.
Reveal Answer & Explanation
Answer: The 'compareTo(String anotherString)' method performs lexicographical (dictionary) comparison based on Unicode/ASCII character values: 1. Returns 0 if both strings have identical characters in identical positions (e.g., '"CAT".compareTo("CAT")' returns 0). 2. Returns a negative integer if the invoking string alphabetically precedes the argument (e.g., '"A".compareTo("B")' returns -1 because 'A' (65) - 'B' (66) = -1). 3. Returns a positive integer if the invoking string alphabetically follows the argument (e.g., '"D".compareTo("A")' returns 3 because 'D' (68) - 'A' (65) = 3).
4
What is the String Constant Pool (SCP)? Why does Java utilize it?
Reveal Answer & Explanation
Answer: The String Constant Pool (SCP) is a dedicated memory caching region located inside the Java Heap specifically designed to store String literals. When a string literal is created (e.g., 'String s = "Delhi";'), the JVM checks the pool; if an identical literal already exists, it reuses the pooled reference rather than allocating new Heap memory. Java utilizes the SCP to minimize memory footprint and optimize runtime performance, since string literals represent the vast majority of string objects in applications.
5
What is the operation of 'str.substring(2, 6)' on the string 'KNOWLEDGE'?
Reveal Answer & Explanation
Answer: The 'substring(beginIndex, endIndex)' method extracts characters starting at beginIndex (inclusive) up to endIndex - 1 (exclusive). In 'KNOWLEDGE' (indices: 0:K, 1:N, 2:O, 3:W, 4:L, 5:E, 6:D, 7:G, 8:E), characters at indices 2, 3, 4, and 5 are extracted, returning the string: 'OWLE'.
6
What is a Pig Latin word? Give an example of converting 'PROGRAM' to Pig Latin.
Reveal Answer & Explanation
Answer: A Pig Latin word is an encoded word formed by finding the first vowel in the word, moving all consonants preceding that vowel to the end of the word, and appending the suffix 'AY'. For 'PROGRAM', the first vowel is 'O' at index 2. The string from index 2 to the end is 'OGRAM', the preceding consonants are 'PR', and appending 'AY' produces the Pig Latin word: 'OGRAMPRAY'.
7
What is the difference between trim() and replace() methods in String?
Reveal Answer & Explanation
Answer: 'trim()' removes only the leading (beginning) and trailing (ending) whitespace characters from a string, leaving any spaces between words completely intact (e.g., ' A B '.trim() yields 'A B'). 'replace(char oldChar, char newChar)' substitutes ALL occurrences of a specified character with a new character throughout the entire string, including spaces, interior characters, and boundaries.
8
Why is StringBuilder preferred over String when modifying text inside loops?
Reveal Answer & Explanation
Answer: Because String is immutable, appending text in a loop creates a new String object and discards the old one in every iteration, generating massive memory garbage and $O(N^2)$ copying overhead. StringBuilder is mutable; its internal character array expands dynamically, allowing characters to be appended in-place in $O(1)$ amortized time without creating temporary Heap objects.
Finished Studying This Chapter?
READY TO PRACTICE?

Timed CBT Practice Tests (Exam Simulator)

Put your concepts to the test with official curriculum-aligned Foundation and Advanced practice tests. Get instant accuracy scores, time metrics, and step-by-step verified explanations.