---
title: "String Handling in Java: The ICSE and CBSE Guide"
description: "String handling in Java for ICSE and CBSE: the method toolkit, equals vs ==, immutability, substring rules, and 5 board programs with real output."
slug: string-handling-in-java
canonical: https://learn.modernagecoders.com/blog/string-handling-in-java/
date: 2026-07-04
dateModified: 2026-07-04
category: "Java"
tags: ["Java", "Strings", "ICSE", "CBSE", "Exam Preparation"]
keywords: ["string handling in java", "java string programs", "string methods in java", "string handling in java icse", "equals vs == in java", "substring in java", "charAt in java"]
readTime: "8 min read"
author: "Modern Age Coders"
---
# String Handling in Java: The ICSE and CBSE Guide

> The method toolkit, the equals trap, immutability, and five board-style programs, every example compiled and run with its real output.

![String handling in Java complete guide for ICSE and CBSE students](/images/blog/string-handling-in-java/00-hero.png)

*By Modern Age Coders · 2026-07-04 · 8 min read*

Ask an ICSE examiner where students bleed marks, and string questions come up immediately. Not because **string handling in Java** is hard, but because it rewards precise method knowledge: exactly what substring includes, exactly what equals compares, exactly why a string never changes. Get those precise, and string questions become the most reliable marks on the paper.

This guide covers the String methods the ICSE and CBSE syllabi lean on, the two traps that cost the most marks, and five board-style programs. Every example below was compiled and executed, and each output shown is the real one.

It pairs with our [50-program ICSE bank](/blog/50-java-programs-for-icse-class-10), where the string family gets eight more programs including Piglatin and initials.

## A String Is a Row of Indexed Characters

Everything in string handling flows from one picture: a String is a row of characters, numbered from 0. The first character sits at index 0, the last at length() - 1, and every method is just a way of asking about, or building from, those positions.

![The string COMPUTER with each character's index from 0 to 7, showing how charAt and substring count positions in Java](/images/blog/string-handling-in-java/01-index-ruler.png)

*Index 0 to length() - 1. Every string method counts from this ruler.*

## The Method Toolkit, in One Program

Here are the workhorse methods in a single tour. Run this once and you have seen most of what the paper can ask.

```java
public class StrTour {
    public static void main(String[] args) {
        String s = "  Computer Applications  ";
        String t = s.trim();
        System.out.println("length()      : " + t.length());
        System.out.println("charAt(3)     : " + t.charAt(3));
        System.out.println("indexOf('A')  : " + t.indexOf('A'));
        System.out.println("substring(9)  : " + t.substring(9));
        System.out.println("toUpperCase() : " + t.toUpperCase());
        System.out.println("replace(a, @) : " + t.replace('a', '@'));
        System.out.println("startsWith    : " + t.startsWith("Comp"));
        System.out.println("endsWith      : " + t.endsWith("ions"));
    }
}
```

```text
length()      : 21
charAt(3)     : p
indexOf('A')  : 9
substring(9)  : Applications
toUpperCase() : COMPUTER APPLICATIONS
replace(a, @) : Computer Applic@tions
startsWith    : true
endsWith      : true
```

Notice trim() ran first: real input often arrives with stray spaces, and trimming before measuring is a habit examiners quietly reward.

![The essential Java String methods for ICSE and CBSE: length, charAt, indexOf, substring, case changes, trim, replace, equals, and compareTo](/images/blog/string-handling-in-java/02-methods.png)

*The toolkit. If a question mentions positions, think charAt and substring. If it mentions comparing, think equals and compareTo.*

## The Trap That Costs the Most Marks: equals vs ==

Two strings holding identical text can still fail an == test, because == compares whether they are the same object in memory, not the same characters. The characters are what you almost always mean.

```java
public class EqualsTrap {
    public static void main(String[] args) {
        String a = "BLUEJ";
        String b = new String("BLUEJ");

        System.out.println(a == b);                  // compares references
        System.out.println(a.equals(b));             // compares characters
        System.out.println(a.equalsIgnoreCase("bluej"));
    }
}
```

```text
false
true
true
```

Same text, yet == said false. Burn the rule in: text is compared with equals() or equalsIgnoreCase(). Reserve == for numbers and characters.

![equals versus == for Java strings: == compares references while equals compares the actual characters](/images/blog/string-handling-in-java/03-equals.png)

*== asks are you the same object. equals() asks do you say the same thing.*

## Strings Never Change: Immutability

A Java String cannot be modified after creation. Methods like toUpperCase() do not change the string; they hand back a new one, and if you do not catch it in a variable, it vanishes.

```java
public class Immutable {
    public static void main(String[] args) {
        String s = "icse";
        s.toUpperCase();                 // result thrown away!
        System.out.println(s);           // still lowercase

        s = s.toUpperCase();             // capture the new string
        System.out.println(s);
    }
}
```

```text
icse
ICSE
```

The first call did nothing visible because its result was discarded. The assignment on the next line is what actually captures the change. Half of all silent string bugs are this one habit.

## substring and charAt, Precisely

Two rules cover nearly every position question: substring(a) runs from index a to the end, and substring(a, b) runs from a up to b minus one, the end index is not included.

```java
public class SubstringDemo {
    public static void main(String[] args) {
        String s = "COMPUTER";
        System.out.println(s.substring(3));       // from index 3 to the end
        System.out.println(s.substring(0, 4));    // 0 to 3, the 4 is NOT included
        System.out.println(s.charAt(0) + "" + s.charAt(s.length() - 1));
    }
}
```

```text
PUTER
COMP
CR
```

PUTER, COMP, and CR: start index included, end index excluded, and first plus last character via charAt. Those three lines are a whole family of exam questions.

## compareTo and Alphabetical Order

compareTo() returns a number, not a boolean: negative when the first string comes earlier alphabetically, zero when identical, positive when it comes later. It is the engine behind sorting names.

```java
public class CompareToDemo {
    public static void main(String[] args) {
        System.out.println("Apple".compareTo("Banana"));   // negative: Apple comes first
        System.out.println("Mango".compareTo("Mango"));    // zero: identical
        System.out.println("Papaya".compareTo("Guava"));   // positive: Papaya comes later
    }
}
```

```text
-1
0
9
```

Read the sign, not the value. The exact numbers vary; negative, zero, or positive is the answer the paper wants.

## Five Board-Style String Programs

Now the toolkit goes to work. These five shapes cover the string questions boards keep rotating.

### 1. Count vowels, consonants, digits, and spaces

**Question:** Write a program to count the vowels, consonants, digits, and spaces in a string.

```java
public class CountTypes {
    public static void main(String[] args) {
        String s = "ICSE 2027 Computer Applications";
        int vowels = 0, consonants = 0, digits = 0, spaces = 0;
        for (int i = 0; i < s.length(); i++) {
            char ch = Character.toLowerCase(s.charAt(i));
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                vowels++;
            else if (ch >= 'a' && ch <= 'z')
                consonants++;
            else if (Character.isDigit(ch))
                digits++;
            else if (ch == ' ')
                spaces++;
        }
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        System.out.println("Digits: " + digits);
        System.out.println("Spaces: " + spaces);
    }
}
```

```text
Vowels: 10
Consonants: 14
Digits: 4
Spaces: 3
```

### 2. Capitalise every word (title case)

**Question:** Write a program to print a sentence with the first letter of every word in capitals.

```java
public class TitleCase {
    public static void main(String[] args) {
        String s = "string handling carries the marks";
        String[] words = s.split(" ");
        String result = "";
        for (int i = 0; i < words.length; i++) {
            result = result + Character.toUpperCase(words[i].charAt(0))
                   + words[i].substring(1) + " ";
        }
        System.out.println(result.trim());
    }
}
```

```text
String Handling Carries The Marks
```

### 3. Find the longest word

**Question:** Write a program to find and print the longest word in a sentence.

```java
public class LongestWord {
    public static void main(String[] args) {
        String s = "practise every single definition daily";
        String[] words = s.split(" ");
        String longest = words[0];
        for (int i = 1; i < words.length; i++) {
            if (words[i].length() > longest.length())
                longest = words[i];
        }
        System.out.println("Longest word: " + longest + " (" + longest.length() + " letters)");
    }
}
```

```text
Longest word: definition (10 letters)
```

### 4. Search for a word with indexOf

**Question:** Write a program to search for a word in a sentence and print the index where it starts.

```java
public class SearchWord {
    public static void main(String[] args) {
        String s = "Java is the language of the ICSE board";
        String target = "ICSE";
        int pos = s.indexOf(target);
        if (pos == -1)
            System.out.println(target + " not found");
        else
            System.out.println(target + " found at index " + pos);
    }
}
```

```text
ICSE found at index 28
```

### 5. Arrange the letters of a word alphabetically

**Question:** Write a program to arrange the characters of a word in alphabetical order.

```java
import java.util.Arrays;
public class SortChars {
    public static void main(String[] args) {
        String s = "BOARDS";
        char[] letters = s.toCharArray();
        Arrays.sort(letters);
        String result = new String(letters);
        System.out.println(s + " -> " + result);
    }
}
```

```text
BOARDS -> ABDORS
```

## The Mistakes Examiners See Every Year

- **Comparing text with ==:** works sometimes, fails unpredictably. equals() every time.
- **Running past the last index:** charAt(s.length()) throws StringIndexOutOfBoundsException. The last valid index is length() - 1.
- **Forgetting substring's exclusive end:** substring(0, 4) gives four characters, indices 0 to 3.
- **Discarding method results:** s.toUpperCase(); alone changes nothing. Assign it: s = s.toUpperCase();
- **Treating compareTo like a boolean:** it returns an int. Test its sign against zero.

> **One habit worth a full grade**

> Whenever a string question involves positions, sketch the index ruler in the margin first: the word with 0, 1, 2... under each letter. Thirty seconds of drawing prevents every off-by-one error the question was designed to trigger.

---

## Frequently Asked Questions

**What is string handling in Java?**

Working with text using the String class and its methods: measuring with length(), reading positions with charAt(), cutting pieces with substring(), searching with indexOf(), changing case, and comparing with equals() and compareTo(). ICSE and CBSE both test it heavily through program questions.

**What is the difference between equals() and == for strings?**

== checks whether two variables point at the same object in memory. equals() checks whether the characters match. For comparing text, equals() or equalsIgnoreCase() is almost always what you mean, and using == instead is the most common string mistake in board answers.

**How does substring() work in Java?**

substring(a) returns everything from index a to the end. substring(a, b) returns indices a up to b minus one; the end index is excluded. So "COMPUTER".substring(0, 4) is COMP, exactly four characters.

**Why are Java strings immutable?**

Once created, a String's characters can never change; every modifying method returns a brand new string. This makes strings safe to share and reuse internally. Practically, it means you must capture results: s = s.trim(), not just s.trim().

**What does compareTo() return?**

An integer: negative if the calling string comes earlier alphabetically, zero if both are identical, positive if it comes later. Exam answers should interpret the sign rather than the exact value.

**Which string programs are asked most in ICSE?**

Counting character types (vowels, consonants, digits, spaces), palindrome and reverse, Piglatin, initials of a name, title case, longest word, and alphabetical arrangements come up again and again. All appear here or in our 50-program ICSE bank.

**Is StringBuffer needed for ICSE Class 10?**

The Class 10 syllabus centres on the String class and its methods. Focus your energy on the toolkit above; it is what the paper actually examines.

## Precise Methods, Reliable Marks

String handling is the rare topic where knowing ten methods precisely beats knowing a hundred vaguely. You now have the ruler, the toolkit, the two traps, and five programs that put them to work. Drill the rest of the family in the [50-program bank](/blog/50-java-programs-for-icse-class-10), or step back to the [Top 20 walkthroughs](/blog/top-20-java-programs-for-icse-class-10) if any of this moved too fast.

And when you want every one of your own string programs checked line by line, our [live Java classes for ICSE students](/java-programming-for-icse-students) do exactly that, for learners aged 6 to 67 across our [courses](/courses).

[Book a Free ICSE Java Demo](/contact)

### Related reading

- [50 Important Java Programs for ICSE Class 10](/blog/50-java-programs-for-icse-class-10)
- [Top 20 Java Programs for ICSE Class 10](/blog/top-20-java-programs-for-icse-class-10)
- [How to Reverse a String in Python](/blog/how-to-reverse-a-string-in-python)

---

*Source: https://learn.modernagecoders.com/blog/string-handling-in-java/*
