String and StringBuffer Methods with Programs (ISC Class 12 Computer Science)
Updated 17 October 2026 · Draft, not yet fact-checked
A Java String is an immutable sequence of characters: methods such as length(), charAt(i), indexOf(), substring(), concat() and replace() return a new value and never change the original. StringBuffer is mutable and changes in place with append(), insert(), reverse(), delete() and setCharAt(). Compare content with equals() or compareTo(), not ==.
Understand String and StringBuffer Methods with Programs
String as a class. String s = "Digital Library"; creates a String object. Characters are numbered from 0, so the last index is s.length() - 1. A String cannot be changed after creation (immutable); a method that appears to change it returns a new String, so write s = s.toUpperCase(); to keep the result.
Common String methods (for s = "Digital Library", 15 characters):
length()gives 15.charAt(8)gives L.indexOf('i')gives 1, the first position;lastIndexOf('i')gives 9; both give -1 if absent.substring(2, 7)gives "gital" (from index 2 up to but not including 7);substring(8)gives "Library".concat(t)or+joins strings.replace('e', 'a')replaces characters.trim()removes leading and trailing spaces.toUpperCase(),toLowerCase().equals(t)andequalsIgnoreCase(t)compare content.compareTo(t)returns a negative number, 0 or a positive number: the difference of the first unequal characters, or of the lengths if one string is a prefix of the other.startsWith(t)andendsWith(t)give boolean.
== versus equals. == compares references, so two separately created Strings with the same text can give false; equals compares the characters.
StringBuffer. A mutable sequence used when a string is changed a lot. append(x) adds at the end, insert(i, x) inserts at index i, reverse() reverses in place, delete(a, b) removes indices a to b - 1, deleteCharAt(i), replace(a, b, str), setCharAt(i, ch), length(), charAt(i). Print it with println(sb); sb.toString() gives a String. StringBuffer has no equals for content comparison; convert with toString().
Typical programs. Palindrome check, reversing a string, counting vowels or words, frequency of a character, and capitalising words. Loop over charAt(i) and test each character.
StringTokenizer and Scanner are in the Objects chapter.
String and StringBuffer Methods with Programs: key facts
- Indexing
- First index 0
- Last index s.length() - 1
- substring(a, b) gives indices a to b - 1
- substring(a) runs to the end
- indexOf returns -1 when absent.
- Comparison methods
- equals compares content
- == compares references
- compareTo gives the difference of first unequal chars
- Equal strings give 0
- Prefix case: the length difference.
- StringBuffer changes
- append(x) adds at the end
- insert(i, x) inserts at i
- reverse() reverses
- setCharAt(i, ch) replaces one char
- delete(a, b) removes a to b - 1
- These change the same object.
- Immutability
- String methods return a new String
- s.toUpperCase() alone leaves s unchanged
- Assign the result: s = s.toUpperCase()
- StringBuffer methods change the object itself.
How to answer String and StringBuffer Methods with Programs questions
Use this routine for string output and programs.
- 1Write the string with its index numbers below each character.
- 2Apply each method to the original string, remembering that String methods do not change it.
- 3For substring(a, b), take indices a to b - 1; for indexOf, find the first match from the left.
- 4For StringBuffer, update the buffer after every call and write its new content.
- 5For a program, loop with charAt(i) and build a result with +, or use a StringBuffer.
- 6Print with the exact spacing asked.
String and StringBuffer Methods with Programs in real life
The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Checking a mirror word
Suppose a word game accepts a word if it reads the same backwards, ignoring capital letters.
Does "Level" pass and does "Java"?
Try it first, then show the solutionSolution
- "Level" reversed is "leveL", and equalsIgnoreCase with "Level" is true.
- "Java" reversed is "avaJ", which differs from "Java".
Answer: Level passes; Java does not.
Memory hook: Reverse it and compare.
Building a ticket code
Suppose a booking program builds a code by appending, inserting and reversing parts of a StringBuffer.
Why use a StringBuffer instead of repeating + on a String?
Try it first, then show the solutionSolution
- Each + on a String creates a new object.
- StringBuffer changes one object in place, so it suits heavy changes.
Answer: StringBuffer is mutable, so repeated changes do not create many new objects.
Memory hook: Buffer = a scratch pad you can rub out.
Tricks to remember String and StringBuffer Methods with Programs
Short memory aids. Say each one aloud once, then use it on a question the same day.
Index from zero, end is exclusive
substring(3, 8) takes 3, 4, 5, 6, 7.
Use it when: Substring questions.
equals is for text
== asks "same object?", equals asks "same letters?".
Use it when: Comparison questions.
String stays, buffer changes
String methods give a new string; buffer methods rub out and rewrite.
Use it when: Immutability questions.
compareTo = first difference
Subtract the first unequal characters; if a prefix, subtract lengths.
Use it when: compareTo values.
String and StringBuffer Methods with Programs: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: charAt · 1 mark · MCQBoard level
If s = "ISC" then s.charAt(1) is
(a) I (b) S (c) C (d) 1
Try it first, then show the solutionSolution
- Index 0 is I, index 1 is S.
Answer: (b) S
Example 2: Several String methods · 3 marks · Short answerHarder board level
Write the output:
String s = "Digital Library";
System.out.println(s.length() + " " + s.indexOf('i') + " " + s.lastIndexOf('i')
+ " " + s.substring(2, 7) + " " + s.charAt(8));Try it first, then show the solutionSolution
- Indices: D0 i1 g2 i3 t4 a5 l6 (space)7 L8 i9 b10 r11 a12 r13 y14, so the length is 15. (1 mark)
- The first i is at 1 and the last i at 9. (1 mark)
- substring(2, 7) takes indices 2 to 6: gital. charAt(8) is L. Output: 15 1 9 gital L. (1 mark)
Answer: 15 1 9 gital L
Example 3: compareTo and equals · 3 marks · Short answerHarder board level
Write the output:
String a = "apple", b = "apricot";
System.out.println(a.compareTo(b));
System.out.println(a.equals("Apple") + " " + a.equalsIgnoreCase("Apple")
+ " " + "abc".compareTo("abcde"));Try it first, then show the solutionSolution
- apple and apricot first differ at index 2: p (112) and r (114), so compareTo gives 112 - 114 = -2. (1 mark)
- equals is case-sensitive: false; equalsIgnoreCase: true. (1 mark)
- "abc" is a prefix of "abcde", so the result is the length difference 3 - 5 = -2. Output lines: -2 and false true -2. (1 mark)
Answer: -2
false true -2
Example 4: StringBuffer operations · 4 marks · Short answerHarder board level
Write the output:
StringBuffer sb = new StringBuffer("ISC");
sb.append(" 2027");
sb.insert(3, "-12");
sb.reverse();
sb.setCharAt(0, '9');
System.out.println(sb + " " + sb.length());Try it first, then show the solutionSolution
- append gives ISC 2027; insert at index 3 gives ISC-12 2027. (1 mark)
- reverse gives 7202 21-CSI. (1.5 marks)
- setCharAt(0, '9') gives 9202 21-CSI; its length is 3 + 3 + 5 = 11. (1 mark)
- Output: 9202 21-CSI 11. (0.5 mark)
Answer: 9202 21-CSI 11
Example 5: Case: palindrome checker · 4 marks · Case-basedHOTS / competency
Suppose a word game uses:
static boolean isPal(String s) {
String r = "";
for (int i = s.length() - 1; i >= 0; i--)
r += s.charAt(i);
return r.equalsIgnoreCase(s);
}(i) Find isPal("Level") and isPal("Java"). (1 mark)
(ii) For String x = new String("ab"); String y = new String("ab"); give the values of x == y and x.equals(y). (1 mark)
(iii) What does s print: String s = "ab"; s.concat("cd"); System.out.println(s); (1 mark)
(iv) Why? (1 mark)
Try it first, then show the solutionSolution
- (i) For Level, r is "leveL" and equalsIgnoreCase gives true; for Java, r is "avaJ", false.
- (ii) x == y is false (two objects); x.equals(y) is true.
- (iii) ab.
- (iv) Strings are immutable: concat returns a new String that was not assigned, so s is unchanged.
Answer: (i) true, false (ii) false, true (iii) ab (iv) immutability
Where students lose marks in String and StringBuffer Methods with Programs
The slips examiners see most often, and what to write instead.
Mistake: Taking substring(a, b) up to b
The end index is excluded.
Wrong working
"Computer".substring(0, 3) gives Comp
Right working
"Computer".substring(0, 3) gives Com
Do this: Count indices a to b - 1.
Usually costs: 1 mark
Mistake: Using == to compare string content
== compares references.
Wrong working
if (s == "yes")
Right working
if (s.equals("yes"))
Do this: Use equals or equalsIgnoreCase.
Usually costs: 1 mark
Mistake: Not assigning the result of a String method
Strings are immutable, so the original is unchanged.
Wrong working
s.toUpperCase(); then use s
Right working
s = s.toUpperCase();
Do this: Store the returned String.
Usually costs: 1 mark
Exam tips
- Write index numbers under the string before answering any method question.
- Remember that the end index of substring is excluded.
- Give compareTo as a number and show the characters compared.
- Use equals, not ==, in every program that compares text.
- For StringBuffer, rewrite the content after each call.
Practice questions on String and StringBuffer Methods with Programs
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
Which StringBuffer method reverses the characters in place?
(a) reverse() (b) invert() (c) flip() (d) turn()Hint
It is spelt as the word.
Answer
(a) reverse()
Q2 · 2 marks · Short answerBoard level
Distinguish between String and StringBuffer.
Hint
One can be changed, the other cannot.
Answer
A String object is immutable: its characters cannot be changed after creation and its methods return new Strings. A StringBuffer is mutable: append, insert, reverse and similar methods change the same object, so it suits heavy modification.
Q3 · 3 marks · Short answerHarder board level
Write the output:
String s = " Java Programming "; String t = s.trim(); System.out.println(t.length() + " " + t.substring(5) + " " + t.replace('a', 'o') + " " + t.toUpperCase().indexOf("PRO"));Hint
Trim first, then use t.
Answer
trim gives "Java Programming" (4 + 1 + 11 = 16 characters). substring(5) is Programming. Replacing a by o gives Jovo Progromming. In upper case the text is JAVA PROGRAMMING and PRO starts at index 5. Output: 16 Programming Jovo Progromming 5
Q4 · 4 marks · Short answerHarder board level
Write a program segment to count the vowels in the string "Education" (any case). Give the count.
Hint
Convert to lower case first.
Answer
String s = "Education".toLowerCase(); int v = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') v++; } System.out.println(v);The vowels of education are e, u, a, i, o: the count is 5.
Q5 · 4 marks · Case-basedHOTS / competency
Trace the program and state the output:
String s = "to be or not", w = "", r = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c != ' ') w += c; else { r = w + " " + r; w = ""; } } r = w + " " + r; System.out.println(r.trim());Also state what the program does and why trim() is needed.
Hint
Each finished word is put in front of the text built so far.
Answer
Words are collected in w. At each space the word is placed before r: "to ", then "be to ", then "or be to ". At the end w = "not", so r becomes "not or be to " and trim removes the trailing space. Output: not or be to. The program reverses the order of the words. trim() is needed because r ends with a space left by the last concatenation.
Test your recall
Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.
1.What does indexOf return when the character is absent?Show answer
-1.
2.Is String mutable?Show answer
No, it is immutable.
3.Which method removes leading and trailing spaces?Show answer
trim().
4.What does compareTo return for equal strings?Show answer
0.
5.Which StringBuffer method adds text at the end?Show answer
append().
6.What does substring(3) give?Show answer
The characters from index 3 to the end.
String and StringBuffer Methods with Programs: frequently asked questions
What is the difference between equals() and == for strings?
equals() compares the characters of the strings; == compares whether both names refer to the same object.
Why is String called immutable?
Because once created its content cannot be changed; methods like replace and toUpperCase return a new String and leave the original unchanged.
When should StringBuffer be used?
When a string is modified many times, such as repeated append, insert or reverse operations, because it changes in place.
What does compareTo return?
A negative number if the first string comes before the second, 0 if equal, and a positive number otherwise; the value is the difference at the first unequal character or of the lengths.