Model G20 2027 at FLAME University, registrations now open

String handling | ICSE Class 10 Computer Applications Notes

29 min read

On this page

This note covers the String class, character positions, joining and converting strings, case conversion, trimming, searching, comparison, substrings, replacement, character traversal, string arrays, linear search, bubble sort and selection sort.

What is a String, and how is a Java string written?

A string is a sequence of characters representing text. A character can be a letter, digit, space or punctuation mark. String is Java's class for strings; a class defines a type of object and its available operations.

An object is an instance of a class. A variable is a named storage location; a String variable holds a reference to a String object. A reference identifies an object rather than containing all its characters directly.

How do literals and data types differ?

A literal is a value written directly in a program. A Java string literal uses double quotation marks, as in "Hello World!". A char literal uses single quotation marks, as in 'H'. String and char are different data types.

A data type specifies the kind of value. The type int represents an integer, char represents one UTF-16 code unit, and boolean represents true or false. UTF-16 is a representation of Unicode text; Unicode assigns codes to characters. A code unit is one storage unit in that representation.

For the ordinary English text used here, each character occupies one such code unit. Consequently, character counting and Java's code-unit counting coincide in these programs. Some other Unicode characters occupy two units, so length() does not universally count visible characters.

Property: String contents are immutable

Definition: An immutable object cannot have its contents changed after creation. Java String objects are immutable. A variable can nevertheless be assigned a reference to a different string.

How should the program notation be read?

In String str1 = "Hello World!";, String declares the type, str1 names the variable, = assigns the value, and ; ends the statement. A method is a named operation. A method call invokes that operation; parentheses enclose its arguments, the supplied values.

A dot selects a member: str1.length() invokes length on str1. Empty parentheses mean that no arguments are supplied. A return value is the result produced by a method. Braces { } enclose a block, a group of declarations or statements.

Each worked program uses class StringDemo to name its containing class. In public static void main(String[] args), public permits access, static permits invocation without creating an instance, void means no value is returned, and main names the program's entry method.

String[] args declares an array of strings named args for command-line arguments; [] denotes an array, an indexed collection. System.out names the standard output stream. Its println method displays a value followed by a new line. Run each worked program separately.

How do length() and charAt() identify characters?

Property: The first character has index zero

An index is a numbered position. Java String positions begin at 0. If n denotes str1.length(), valid indices run from 0 to n - 1. Here - denotes subtraction. An index is different from an ordinary position counted from one.

Rule: str1.length() returns an int count of UTF-16 units. str1.charAt(index) returns the char at the supplied integer index. For these English strings, this is the character at that position.

A space contributes to length just as a letter does. Quotation marks delimiting the literal are not stored as part of its text. The empty string, written "", has length 0 and has no valid character index.

How is an access traced?

Worked example 1. Find the length, first character and last character of "Hello World!".

class StringDemo {
public static void main(String[] args) {
String str1 = "Hello World!";
int n = str1.length();
System.out.println(n);
System.out.println(str1.charAt(0));
System.out.println(str1.charAt(n - 1));
}
}

Answer: Output, in order:
12
H
!

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Declares str1 and assigns the given text, including its space and exclamation mark.
  4. Line 4: Declares n and stores the length, 12, returned by length().
  5. Line 5: Displays the stored length as the first output line.
  6. Line 6: Accesses index 0 and displays H, the first character.
  7. Line 7: Calculates the final valid index, 11, and displays the exclamation mark.
  8. Lines 8 and 9 close main and the class respectively.

Bounds are the permitted limits of an index. Accessing charAt(n) is outside the bounds because n counts the characters, while numbering begins at 0. A negative index is also invalid in Java. Such access causes an exception, an abnormal execution event.

Before accessing a character, establish both the string's length and the requested index. When text is reassigned, calculate positions from the current string. A previously valid position can become invalid if the replacement text is shorter.

How are strings joined and values converted into text?

Property: Concatenation joins strings

Concatenation means joining strings in order. The call str1.concat(str2) returns str1 followed by str2, where str2 names the second String. It inserts neither a space nor punctuation. Any required separator must already occur in the supplied strings.

The + operator also concatenates when a String operand is involved; an operand is a value on which an operator acts. Without a string operand, + can perform numerical addition. Identify the operand types before interpreting an expression.

Syntax: String.concat takes a String argument and returns a String. To retain the joined result, assign it to a variable or use it directly in another operation, such as printing.

What remains after concatenation?

Worked example 2. Join "Hello" and "World!", then display the unchanged first string and its length converted into text.

class StringDemo {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World!";
System.out.println(str1.concat(str2));
System.out.println(str1);
System.out.println(String.valueOf(str1.length()));
}
}

Answer: Output, in order:
HelloWorld!
Hello
5

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Declares str1 with the first supplied string.
  4. Line 4: Declares str2 with the second supplied string; neither string supplies an intervening space.
  5. Line 5: Prints the joined result without assigning it back to str1.
  6. Line 6: Prints Hello, showing that the original String contents were not modified.
  7. Line 7: Calls length() to obtain 5, converts that integer to a String with valueOf, then prints the resulting text.
  8. Lines 8 and 9 close main and the class respectively.

What does valueOf() do?

String.valueOf converts a supplied value to its string representation. It is a static method called using the class name String. Its overloaded forms accept different argument types; overloading means providing methods with the same name but different parameter lists.

A parameter is a variable declared to receive an argument. The valueOf forms handle values such as integers, characters and booleans; the char-array form produces text from its characters. The resulting text is a String, even when its displayed characters are digits.

Do not confuse conversion into text with conversion from text into a number. The length of the converted string counts its text units; it does not recover the original numerical value. Choose conversion direction according to what the next operation requires.

How do trim() and case conversion affect strings?

Leading characters occur before the main text; trailing characters occur after it. trim() returns text with leading and trailing characters whose codes are at most that of the ordinary space removed. It does not remove spaces between words.

Uppercase means capital letters; lowercase means small letters. toUpperCase() and toLowerCase() return case-converted strings. They do not alter the original String object. Retain the result through assignment when subsequent work needs the converted text.

Note: Case conversion uses the default locale, the language and regional setting. The examples here use ordinary English letters with straightforward conversions. Do not assume that all Unicode case conversions preserve length.

How is a returned conversion used?

Worked example 3. For "hello WORLD!", display both case conversions, the trimmed result and the original length.

class StringDemo {
public static void main(String[] args) {
String str1 = "hello WORLD!";
System.out.println(str1.toLowerCase());
System.out.println(str1.toUpperCase());
System.out.println(str1.trim());
System.out.println(str1.length());
}
}

Answer: Output, in order:
hello world!
HELLO WORLD!
hello WORLD!
12

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Stores the supplied mixed-case text; mixed case combines capital and small letters.
  4. Line 4: Prints the lowercase result, leaving the stored string unchanged.
  5. Line 5: Prints the uppercase result, again without assigning it back.
  6. Line 6: Prints the same visible text because it has no leading or trailing spaces; its internal space remains.
  7. Line 7: Prints 12, the length of the original string including the internal space and punctuation.
  8. Lines 8 and 9 close main and the class respectively.

Assignment changes which value a variable holds. Thus str1 = str1.trim(); retains the returned trimmed value in str1. A call written merely as str1.trim(); computes a result but does not replace the value stored in str1.

When tracing a sequence, distinguish a discarded result from an assigned one. Mark the current value after each assignment. This prevents a later length, character access or comparison from being evaluated against text that the program never stored.

How can characters and string beginnings or endings be located?

indexOf(char) returns the index of the first occurrence of the specified character. lastIndexOf(char) returns its final occurrence. An occurrence is one place where the searched character appears. Both methods return -1 when that character is absent.

The argument supplies a character, while the return value is an integer position. Neither method returns the number of occurrences. A first occurrence can be at index 0, so a successful search must not be restricted to positive results.

MethodReturn typeQuestion answered
indexOf(char)intWhere does this character first occur?
lastIndexOf(char)intWhere does this character last occur?
startsWith(String)booleanDoes the string begin with this text?
endsWith(String)booleanDoes the string end with this text?

How do position searches differ from boundary tests?

Worked example 4. Search for the letter o in "Hello World!" and test its beginning and ending.

class StringDemo {
public static void main(String[] args) {
String str1 = "Hello World!";
System.out.println(str1.indexOf('o'));
System.out.println(str1.lastIndexOf('o'));
System.out.println(str1.startsWith("He"));
System.out.println(str1.endsWith("World!"));
}
}

Answer: Output, in order:
4
7
true
true

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Stores the complete text to be searched.
  4. Line 4: Prints 4 because the first o occurs at index 4.
  5. Line 5: Prints 7 because the last o occurs at index 7.
  6. Line 6: Prints true because He matches the beginning exactly.
  7. Line 7: Prints true because World! matches the ending, including its punctuation.
  8. Lines 8 and 9 close main and the class respectively.

A prefix is text at the beginning of a string, and a suffix is text at its end. startsWith and endsWith compare the supplied text at these boundaries. They are case-sensitive, meaning capital and small letters are distinguished.

Choose the method by the information needed. Use indexOf for a numerical position, startsWith for a prefix condition and endsWith for a suffix condition. A boolean result reports whether a condition holds; it supplies no character position.

How are string equality and ordering compared?

equals compares string contents with case sensitivity. equalsIgnoreCase compares contents while ignoring letter-case differences. Both return boolean values. Equality requires a match across the complete strings, rather than merely finding one string at the beginning of another.

The == operator tests reference equality for String operands, meaning whether both references identify the same object. It is not a substitute for equals when the task is to compare text. Two distinct String objects can contain matching text.

How should compareTo results be interpreted?

compareTo performs lexicographic comparison, examining corresponding UTF-16 units in order. At the first difference, it returns the first differing unit of the calling string minus the corresponding unit of the argument. If one string is a prefix of the other, it returns their length difference.

Result of first.compareTo(second)MeaningOrdering decision
Less than 0first precedes secondKeep this order for ascending sorting
Equal to 0Both strings have equal contentsNo exchange is needed for this pair
Greater than 0first follows secondExchange this pair for ascending sorting

Here first and second name the two compared strings. Ascending order places earlier values before later values under the chosen comparison. compareToIgnoreCase performs an ordering comparison that ignores case; its negative, zero and positive results have the same ordering meanings.

Rule: Use the sign of a comparison result to decide order. Do not assume that an unequal comparison returns exactly -1 or 1. Case-sensitive code order can differ from ordinary dictionary expectations for mixed-case text.

Worked example 5. Compare "hello WORLD!" with "HELLO WORLD!", then compare the original string with itself.

class StringDemo {
public static void main(String[] args) {
String str1 = "hello WORLD!";
String str2 = "HELLO WORLD!";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str1.compareToIgnoreCase(str2));
System.out.println(str1.compareTo(str1));
}
}

Answer: Output, in order:
false
true
0
0

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Declares the first string with its supplied mixed case.
  4. Line 4: Declares the second string using the uppercase text.
  5. Line 5: Prints false because corresponding letter cases differ.
  6. Line 6: Prints true because ignoring case makes the complete strings equal.
  7. Line 7: Prints 0 because comparison ignoring case finds no difference.
  8. Line 8: Prints 0 because comparing identical text produces equality.
  9. Lines 9 and 10 close main and the class respectively.

How are substrings extracted and characters replaced?

A substring is a contiguous part of a string: its characters are adjacent in the original order. substring(beginIndex) returns text from beginIndex to the end. Here beginIndex is the integer position at which extraction begins.

substring(beginIndex, endIndex) begins at beginIndex and stops before endIndex. The second argument, endIndex, is an exclusive boundary: the character at that position is not included. A comma separates arguments. Valid extraction includes the start and excludes the end.

Rule: For the two-argument substring call, 0 ≤ beginIndex ≤ endIndex ≤ length(). The symbol ≤ means less than or equal to. The result's length is endIndex - beginIndex. Equal boundaries produce an empty string.

How does replacement differ from extraction?

replace(oldChar, newChar) returns text in which every occurrence of oldChar is replaced by newChar. Both arguments are char values. The original String remains unchanged. This form replaces matching characters throughout the string, not just their first occurrence.

Worked example 6. Extract "ello" and "World!" from "Hello World!", then replace every o with an asterisk.

class StringDemo {
public static void main(String[] args) {
String str1 = "Hello World!";
System.out.println(str1.substring(1, 5));
System.out.println(str1.substring(6));
System.out.println(str1.replace('o', '*'));
System.out.println(str1.length());
}
}

Answer: Output, in order:
ello
World!
Hell* W*rld!
12

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Stores the given original string.
  4. Line 4: Extracts indices 1 through 4; index 5 is excluded, producing ello.
  5. Line 5: Extracts from index 6 through the final character, producing World!.
  6. Line 6: Replaces both occurrences of o in the returned text. Here * is an asterisk character, not a multiplication operation.
  7. Line 7: Prints the original length 12 because none of the preceding results was assigned to str1.
  8. Lines 8 and 9 close main and the class respectively.

Java substring does not silently shorten an end index beyond the string's length. Invalid boundaries cause an exception. Likewise, a begin index after the end index is invalid. Establish the permitted interval before copying text or predicting output.

To modify one selected position while retaining other equal characters, construct a result from the prefix, replacement character and suffix. Do not use replace when the requirement is to change only one occurrence. The selected position determines the two extraction boundaries.

How does a loop process characters one at a time?

Traversal means visiting the characters of a string in sequence. A loop is a construct that repeats instructions. A for loop combines initialisation, a continuation condition and an update; semicolons separate these three parts inside its parentheses.

In the following program, i names the current index and count stores the number of matches found. The operator < means less than. The update i++ increases i by one after an iteration, one execution of the loop's body.

An if statement performs an action when its condition is true. For char values, == compares their values. Thus a character test can use ==, whereas whole-string content comparison uses equals. Keeping those different operand types clear prevents incorrect tests.

How is a frequency counted?

Worked example 7. Count occurrences of the character a in the supplied text "Today is a Holiday".

class StringDemo {
public static void main(String[] args) {
String str1 = "Today is a Holiday";
int count = 0;
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) == 'a') count++;
}
System.out.println(count);
}
}

Answer: Output, in order:
3

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Stores the complete text with all internal spaces.
  4. Line 4: Initialises count to 0 because no characters have yet been examined.
  5. Line 5: Starts i at 0, continues while i is below the length and advances i after each iteration.
  6. Line 6: Compares the current character with a and increments count only when that comparison is true.
  7. Line 7: Closes the repeated block so the next loop test follows.
  8. Line 8: Prints 3 after traversal: one a occurs in Today, one is the separate word a and one occurs in Holiday.
  9. Lines 9 and 10 close main and the class respectively.

A counter records how many matches have been found. Initialise it before the loop, update it inside the loop, and print the final total after the loop. Initialising inside the loop would discard the total accumulated during earlier iterations.

Reverse traversal starts at length() - 1 and decreases the index until index 0 has been processed. A reverse can be displayed directly or accumulated in a new String. A palindrome reads identically forwards and backwards under the specified comparison rule.

For a case-sensitive palindrome test, compare corresponding characters from opposite ends, or compare the original with its reverse using equals. Decide explicitly whether case and spaces matter. A test that ignores them solves a different problem from an exact character-by-character test.

How does a string array support linear search?

A String array stores String references in indexed elements. An element is one entry in the array. String[] words declares words as an array of strings. An initialiser lists its starting elements inside braces, separated by commas.

In words[i], i selects an array element; words[i].charAt(j) would select a character inside that element, with j naming the character index. The array and the selected string therefore have separate lengths and separate valid index ranges.

Syntax: words.length is the number of array elements, without parentheses. words[i].length() is the length of the String stored at index i, with parentheses. These operations count different things.

How does the first matching position get recorded?

Linear search examines array elements in sequence. The following program uses key for the required string and position for its first matching index. The initial value -1 is a sentinel, a special value meaning that no match has been found.

Worked example 8. Search the array {"India", "is", "a", "Great", "Country"} for "Great", using exact case-sensitive matching. Print its zero-based index, or -1 if absent.

class StringDemo {
public static void main(String[] args) {
String[] words = {"India", "is", "a", "Great", "Country"};
String key = "Great";
int position = -1;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(key)) {
position = i;
break;
}
}
System.out.println(position);
}
}

Answer: Output, in order:
3

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Declares words and initialises its five String elements in the specified order.
  4. Line 4: Stores the exact search text in key.
  5. Line 5: Records the not-found sentinel before searching.
  6. Line 6: Examines valid array indices from the beginning until the array ends, unless the loop exits earlier.
  7. Line 7: Tests whether the current element has the same contents as key.
  8. Line 8: Records the index of the matching element.
  9. Line 9: Uses break to exit the nearest enclosing loop immediately, preserving the first match.
  10. Line 10: Closes the conditional block.
  11. Line 11: Closes the loop body.
  12. Line 12: Prints 3 because Great is the fourth element and array indexing starts at 0.
  13. Lines 13 and 14 close main and the class respectively.

break stops the search once the desired first match is found. Without a match, the loop completes and position remains -1. Linear search does not require the array to be sorted, and the comparison determines whether matching is case-sensitive.

How do bubble sort and selection sort arrange strings?

Sorting rearranges elements according to a comparison rule. Both programs below use ascending, case-sensitive compareTo order on the same supplied array. For mixed-case text, this is code-unit order; it does not put all words into case-insensitive dictionary order.

How does bubble sort exchange adjacent elements?

Bubble sort repeatedly compares neighbouring elements and exchanges a pair when it is out of order. An exchange is a swap. A pass is one sweep of comparisons. After a complete ascending pass, the greatest remaining element reaches the end of the unsorted part.

In the program, pass counts completed sweeps, j selects the left member of an adjacent pair, and temp temporarily stores a string during a swap. The operator > means greater than; j + 1 selects the right member.

Worked example 9. Bubble-sort {"India", "is", "a", "Great", "Country"} in ascending case-sensitive compareTo order and display every element.

class StringDemo {
public static void main(String[] args) {
String[] words = {"India", "is", "a", "Great", "Country"};
for (int pass = 0; pass < words.length - 1; pass++) {
for (int j = 0; j < words.length - 1 - pass; j++) {
if (words[j].compareTo(words[j + 1]) > 0) {
String temp = words[j];
words[j] = words[j + 1];
words[j + 1] = temp;
}
}
}
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
}
}

Answer: Output, in order:
Country
Great
India
a
is

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Stores the specified starting array; its length is 5.
  4. Line 4: Runs four passes, sufficient for this five-element array.
  5. Line 5: Visits adjacent pairs in the unsorted part, excluding the already settled tail.
  6. Line 6: Tests whether the left string follows the right string under compareTo.
  7. Line 7: Saves the left element before overwriting its array position.
  8. Line 8: Moves the right element into the left position.
  9. Line 9: Moves the saved element into the right position, completing the swap.
  10. Line 10: Closes the conditional swap block.
  11. Line 11: Closes the inner comparison loop.
  12. Line 12: Closes the outer pass loop.
  13. Line 13: Traverses the sorted array from its first element to its last.
  14. Line 14: Prints the current element on its own line.
  15. Line 15: Closes the display loop.
  16. Lines 16 and 17 close main and the class respectively.

How does selection sort choose the next element?

Selection sort finds the smallest element in the remaining unsorted part and swaps it into that part's first position. Here i marks that destination, smallest records the index of the smallest string found so far, and j scans later candidates.

Worked example 10. Selection-sort {"India", "is", "a", "Great", "Country"} using the same ascending case-sensitive comparison, then display every element.

class StringDemo {
public static void main(String[] args) {
String[] words = {"India", "is", "a", "Great", "Country"};
for (int i = 0; i < words.length - 1; i++) {
int smallest = i;
for (int j = i + 1; j < words.length; j++) {
if (words[j].compareTo(words[smallest]) < 0) smallest = j;
}
String temp = words[i];
words[i] = words[smallest];
words[smallest] = temp;
}
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
}
}

Answer: Output, in order:
Country
Great
India
a
is

  1. Line 1 declares StringDemo, the class containing this independent program.
  2. Line 2 opens main, the method from which execution starts.
  3. Line 3: Initialises the array with the same five supplied elements.
  4. Line 4: Selects each destination except the final position, which is settled by the earlier passes.
  5. Line 5: Starts by treating the destination element as the smallest remaining candidate.
  6. Line 6: Examines each later candidate in the unsorted portion.
  7. Line 7: Records a new smallest index whenever the candidate precedes the current smallest string.
  8. Line 8: Closes the candidate-search loop before performing the swap.
  9. Line 9: Saves the element currently at the destination.
  10. Line 10: Places the selected smallest string at the destination.
  11. Line 11: Places the saved element in the selected position.
  12. Line 12: Closes the outer sorting loop.
  13. Line 13: Traverses the complete sorted array.
  14. Line 14: Prints each element on its own line.
  15. Line 15: Closes the display loop.
  16. Lines 16 and 17 close main and the class respectively.

The two algorithms produce the same final order here but perform different intermediate operations. Bubble sort swaps neighbouring out-of-order elements during a pass. Selection sort records the smallest remaining element during its scan and then places that selected element.

To sort while ignoring case, apply compareToIgnoreCase consistently throughout the chosen algorithm. Changing the comparison changes the intended ordering. Specify that rule in the problem before tracing passes, particularly when some words begin with capitals and others with small letters.

Glossary

  • String — Java class representing immutable text as a sequence of UTF-16 code units.
  • Literal — A value written directly in source code, rather than obtained from a variable.
  • Index — An integer position identifying a character unit or array element, starting at zero.
  • Immutability — The inability to change an object's contents after that object has been created.
  • Method — A named operation that can receive arguments and may return a result.
  • Argument — A value supplied to a method when that method is called.
  • Concatenation — Joining strings in sequence to produce text containing their characters in order.
  • Substring — A contiguous portion of a string, retaining the original order of its characters.
  • Lexicographic comparison — Comparing corresponding character units in order, resolving ordering at the first difference.
  • Traversal — Visiting successive positions to process each character or array element in turn.
  • Linear search — Examining array elements in sequence to find one matching a specified key.
  • Bubble sort — Sorting through repeated passes that compare adjacent elements and exchange out-of-order pairs.
  • Selection sort — Sorting by selecting the smallest remaining element for each successive destination position.
  • Sentinel — A special value used to indicate a state, such as an unsuccessful search.

Common errors and misconceptions

  • Misconception: The final character is at index length(). Correct: In a non-empty string it is at length() - 1, because numbering starts at zero. Calling charAt(length()) is outside the valid range.
  • Misconception: charAt accepts negative positions to count from the end. Correct: Java requires a non-negative index below the string length. Calculate the required position explicitly before calling charAt.
  • Misconception: Case conversion changes the original String object. Correct: It returns a result. Assign that result if later operations must use the converted text; the original object's contents remain immutable.
  • Misconception: == checks whether two strings contain the same text. Correct: For String references it checks object identity. Use equals for exact content equality or equalsIgnoreCase when case should be ignored.
  • Misconception: substring includes the character at its end index. Correct: The end boundary is exclusive. For valid boundaries, subtract the beginning index from the end index to obtain the returned length.
  • Misconception: compareTo returns exactly 1 whenever the first string comes later. Correct: Its positive sign indicates later ordering; the magnitude can differ. Sorting should test the sign.
  • Misconception: An array's length and a String's length use identical syntax. Correct: Use words.length for array elements and words[i].length() for the selected string's text length.
  • Misconception: trim removes every space. Correct: It removes qualifying leading and trailing characters. Internal spaces remain, so it cannot be used to delete all spaces between words.

Exam-style questions with model answers

Q1. Given String str1 = "Hello World!";, state str1.length() and str1.charAt(0), explaining each result. [2 marks]
  1. str1.length() returns 12, counting the letters, internal space and exclamation mark, but excluding the delimiting quotation marks.
  2. str1.charAt(0) returns the character H because the first character of a Java string occupies index zero.
Q2. Given String str1 = "Hello World!";, state and explain str1.substring(1, 5), str1.substring(6) and str1.replace('o', '*'). [3 marks]
  1. str1.substring(1, 5) returns "ello". Extraction starts at index 1 and includes indices 1 through 4; the end boundary 5 is excluded.
  2. str1.substring(6) returns "World!". With one argument, extraction begins at the supplied position and continues through the original string's final character.
  3. str1.replace('o', '*') returns "Hell* W*rld!". Both occurrences of o are replaced in the returned String; str1 still holds the original text.
Q3. Given String str1 = "hello WORLD!"; and String str2 = "HELLO WORLD!";, state and explain str1.equals(str2), str1.equalsIgnoreCase(str2) and str1.compareToIgnoreCase(str2). [3 marks]
  1. str1.equals(str2) returns false. This method compares the complete contents with case sensitivity, and corresponding letters in the first word have different cases.
  2. str1.equalsIgnoreCase(str2) returns true. Ignoring letter case makes all corresponding characters match, including the space and exclamation mark in both strings.
  3. str1.compareToIgnoreCase(str2) returns 0. This is an integer ordering result expressing equality under comparison ignoring case, rather than the boolean value true.
Q4. Given String str1 = "Hello World!";, state and explain str1.indexOf('o'), str1.lastIndexOf('o'), str1.startsWith("He") and str1.endsWith("World!"). [4 marks]
  1. str1.indexOf('o') returns 4, the index of the first occurrence of o when positions are numbered from zero.
  2. str1.lastIndexOf('o') returns 7, the index of the final occurrence of o in the complete supplied string.
  3. str1.startsWith("He") returns true because the first two characters match the supplied prefix exactly, with matching case.
  4. str1.endsWith("World!") returns true because the supplied suffix matches the final characters, including the exclamation mark.
Q5. A Java program counts occurrences of the character 'a' in "Today is a Holiday". Give five ordered steps of an algorithm, including the starting counter, valid traversal bounds, comparison, update and final result. Match case exactly. [5 marks]
  1. Store the given string in str1 and initialise an integer variable count to 0. This represents the number of matching characters found before traversal begins.
  2. Traverse using an integer index i beginning at 0 and continuing while i is less than str1.length(). Advance i by one after each iteration.
  3. At each visited position, obtain the character with str1.charAt(i). Compare this char with 'a' using ==, preserving the requested case-sensitive comparison.
  4. Increase count by one whenever the character equals a; leave count unchanged for other characters. Keep the same counter throughout the traversal.
  5. After all positions have been examined, display 3. The matches are the a in Today, the separate word a and the a in Holiday.
Q6. Given String[] words = {"India", "is", "a", "Great", "Country"}; and the search key "Great", explain a linear search for the first exact match in five points. Print the zero-based index if found and -1 otherwise. [5 marks]
  1. Set an integer variable position to -1 before examining any element. This sentinel is outside the valid array indices and represents an unsuccessful search.
  2. Start an integer index i at 0 and inspect elements while i is less than words.length. The supplied array need not be sorted first.
  3. Compare each current element using words[i].equals("Great"). This checks the complete String contents with case sensitivity rather than testing whether references identify the same object.
  4. When a match is found, assign i to position and exit the loop with break. Stopping immediately preserves the index of the first exact match.
  5. Print position after the loop. The result is 3 because Great is at index 3 in the supplied array; without a match, -1 would remain.
Q7. For the array {"India", "is", "a", "Great", "Country"}, describe ascending selection sort using case-sensitive String.compareTo. State its final order. Give five points covering selection, comparison, swapping, repetition and output. [5 marks]
  1. Start at the first unsorted position and treat its element as the smallest remaining candidate. Record its index so that the selected element can later be moved.
  2. Scan the later elements. Whenever a candidate.compareTo(currentSmallest) result is negative, record that candidate as the new smallest element; continue until the remaining part is examined.
  3. Swap the selected smallest element with the element at the current destination. Use temporary storage so that neither of the two String references is lost.
  4. Move the destination one position forward and repeat the search and placement in the remaining unsorted part. The already selected prefix remains in ascending order.
  5. The final order is Country, Great, India, a, is. This follows case-sensitive code-unit comparison, so the capital-initial words here precede the small-letter-initial words.

Key takeaways

  • Java String objects are immutable, although a String variable can be assigned a different returned string.
  • For a non-empty string, valid charAt indices begin at zero and end one below length().
  • Use equals for exact string contents and equalsIgnoreCase when the comparison should ignore letter case.
  • Use the sign of compareTo to determine order; unequal results need not be exactly one or minus one.
  • substring includes its beginning position and excludes its end boundary; replace(char, char) replaces every matching character.
  • trim preserves internal spaces, and case-conversion results must be used directly or assigned if subsequent operations need the converted text.
  • Array length counts elements, whereas a selected String's length() counts its UTF-16 units, including stored spaces.
  • Linear search examines successive elements; bubble sort exchanges adjacent pairs, while selection sort repeatedly places the smallest remaining element.

Test yourself

Why does "Hello World!" have length 12 rather than 11?

The internal space contributes to the length along with the letters and exclamation mark.

Given String str1 = "Hello World!";, what does str1.charAt(str1.length() - 1) return?

It returns the exclamation mark, the character at the final valid index, 11.

What type of result does String.valueOf(12) return?

It returns a String containing the text "12", rather than an integer for arithmetic.

Why can ignoring the return value of toUpperCase() leave later output unchanged?

The method does not change the original String contents; its returned value must be used or assigned.

What does a negative compareTo result mean?

The calling string precedes the argument string under the method's case-sensitive lexicographic comparison.

Given String str1 = "Hello World!";, what does str1.substring(1, 5) return?

It returns "ello", including indices 1 through 4 and excluding the boundary at index 5.

Why is -1 useful as the starting result of an array search?

Valid array indices are non-negative, so -1 can unambiguously indicate that no match was found.

How does selection sort differ from bubble sort during a pass?

Selection sort identifies the smallest remaining element before placing it; bubble sort exchanges out-of-order adjacent elements as it scans.