TutorialsISCClass 11Computer Science

String Handling in Java for ISC Class 11: Methods, StringTokenizer and Programs

ISC Class 11 Computer Science notes on string handling in Java: the String methods you must know, string immutability, comparing strings, splitting a sentence into words with split() and StringTokenizer, and solved sentence programs.

12 min read
String Handling in Java for ISC Class 11: Methods, StringTokenizer and Programs

Sentence and word programs are one of the most common question types in both the ISC theory paper and the ISC practical exam. They all build on a small set of String methods and one key technique: splitting a sentence into words. These notes cover both, with solved programs.

Strings are immutable

A String object cannot be changed after it is created. Methods such as toUpperCase() or replace() return a new string; the original stays the same.

String s = "java";
s.toUpperCase();          // the result is thrown away
System.out.println(s);    // java
s = s.toUpperCase();      // store the new string
System.out.println(s);    // JAVA

String methods you must know

  • length(): the number of characters. "ISC".length() is 3.
  • charAt(i): the character at index i. "ISC".charAt(1) is 'S'.
  • indexOf(ch) / indexOf(str): the first position, or −1 if absent. "banana".indexOf('n') is 2.
  • lastIndexOf(ch): the last position. "banana".lastIndexOf('a') is 5.
  • substring(a) / substring(a, b): from index a to the end, or from a to b − 1. "COMPUTER".substring(3, 6) is "PUT".
  • toUpperCase() / toLowerCase(): change the case.
  • trim(): removes leading and trailing spaces.
  • equals(s) / equalsIgnoreCase(s): compare contents. "Java".equalsIgnoreCase("JAVA") is true.
  • compareTo(s): the difference of the first unequal characters (or of the lengths). "apple".compareTo("apricot") is 'p' − 'r' = −2.
  • startsWith(s) / endsWith(s): "ISC2027".endsWith("27") is true.
  • replace(a, b): replaces every occurrence. "a-b-c".replace('-', ' ') is "a b c".
  • concat(s): joins strings. "Hi".concat("!") is "Hi!".
Never compare strings with ==. It compares references, not contents. Always use equals().

Splitting a sentence into words

Method 1: split()

String sent = "JAVA IS FUN";
String words[] = sent.split(" ");      // {"JAVA", "IS", "FUN"}
System.out.println(words.length);      // 3

If words may be separated by more than one space, use sent.trim().split("\\s+").

Method 2: StringTokenizer (java.util)

import java.util.StringTokenizer;

StringTokenizer st = new StringTokenizer("MADAM ARORA TEACHES.", " .");
int n = st.countTokens();               // 3
while (st.hasMoreTokens())
    System.out.println(st.nextToken());

The second argument lists every delimiter, so here both spaces and full stops separate words. That is handy for ISC sentences, which end in ., ? or !.

Solved program 1: count the palindrome words

Question: Accept a sentence in uppercase that ends with ., ? or !, and count the palindrome words in it.

Example: MADAM ARORA TEACHES MALAYALAM. gives Palindrome words: 3.

import java.util.Scanner;
import java.util.StringTokenizer;

class PalindromeWords {
    static boolean isPalindrome(String w) {
        int i = 0, j = w.length() - 1;
        while (i < j) {
            if (w.charAt(i) != w.charAt(j))
                return false;
            i++;
            j--;
        }
        return true;
    }

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String s = sc.nextLine().trim().toUpperCase();
        char last = s.charAt(s.length() - 1);
        if (last != '.' && last != '?' && last != '!') {
            System.out.println("INVALID INPUT");
            return;
        }
        StringTokenizer st = new StringTokenizer(s, " .?!");
        int count = 0;
        while (st.hasMoreTokens()) {
            String w = st.nextToken();
            if (isPalindrome(w)) {
                System.out.print(w + " ");
                count++;
            }
        }
        System.out.println();
        System.out.println("Palindrome words: " + count);
    }
}

Solved program 2: reverse the order of words

Question: Input a sentence and print its words in reverse order. For example, JAVA IS FUN becomes FUN IS JAVA.

import java.util.Scanner;

class ReverseOrder {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String words[] = sc.nextLine().trim().split("\\s+");
        String result = "";
        for (int i = words.length - 1; i >= 0; i--)
            result += words[i] + " ";
        System.out.println(result.trim());
    }
}

Exam and practical tips

  1. Validate first. ISC practical questions almost always state the valid terminators (., ? or !) and expect "INVALID INPUT" for anything else.
  2. Convert the sentence to one case (usually uppercase) before comparing letters.
  3. Remove the terminator before splitting, or include it in the StringTokenizer delimiters, so the last word doesn't end with a dot.
  4. Test with a one-word sentence and with extra spaces between words.

Practise more sentence programs in our 7 ISC Practical Programs with Solutions and the ISC Practical 2027 series.