In this lesson, you will learn
Here’s an overview organized into categories such as query, comparison, and searching of a String.

The following are the String query methods.
length(), charAt(), toCharArray(), getChars(), substring(), isEmpty(), contains(), endsWith(), startWidth().
The length() method of the String class returns the number of characters contained in the string.
public int length()
public class Main {
public static void main(String[] args) {
String greeting = "Hello, World!";
int length = greeting.length();
System.out.println("The length of the string is: " + length);
}
}
The length of the string is: 13
Returns the character at the specified index of the string.
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where must be nonnegative
String str = "Hello, World!";
char ch = str.charAt(1); // 'e'
Converts the string to a new character array.
char[ ] toCharArray( )
It returns an array of characters for the entire string.
String str = "Hello, World!";
char[] chars = str.toCharArray();
// ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
Extract more than one character into the destination character array at a time.
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
srcBegin – the index of the first character in the string to copy.srcEnd – the index after the last character in the string to copy.dst – the destination array to copy the characters into.dstBegin – the starting index in the destination array where the characters will be copied.
String str = "Hello, World!";
char[] dst = new char[7];
str.getChars(0, 7, dst, 0);
// dst contains ['H', 'e', 'l', 'l', 'o', ',', ' ']
Returns a new string that is a substring of this string. It has 2 forms
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin and returns a copy of the substring that begins at startIndex and runs to the end of the invoking string.
String substring(int startIndex, int endIndex)
The substring begins at the specified beginIndex and extends to the character at index endIndex-1.
String str = "Hello, World!";
String sub1 = str.substring(7); // "World!"
String sub2 = str.substring(0, 5); // "Hello"
true if the string has a length of 0, otherwise false.
String str1 = "";
System.out.println(str1.isEmpty()); // true
String str2 = "Hello";
System.out.println(str2.isEmpty()); // false
CharSequence s – the sequence to search for.true if the sequence of char values is found, otherwise false.
String sentence = "Hello, World!";
System.out.println(sentence.contains("World")); // true
System.out.println(sentence.contains("world")); // false (case-sensitive)
In Java, the startsWith() and endsWith() methods are used to check if a string starts or ends with a specified prefix or suffix, respectively.
The startsWith() method tests if the string starts with the specified prefix. It has two forms:
boolean startsWith(String prefix): Checks if the string starts with the specified prefix.boolean startsWith(String prefix, int offset): Checks if the string starts with the specified prefix beginning a specified index or offset.
String str = "Java Programming";
boolean result1 = str.startsWith("Java"); // true
boolean result2 = str.startsWith("java");
// false, because case-sensitive
boolean result3 = str.startsWith("Programming", 5); // true,
//starts checking from index 5
System.out.println("Starts with 'Java'? " + result1);
System.out.println("Starts with 'java'? " + result2);
System.out.println("Starts with 'Programming' from index 5? " + result3);
The endsWith() method tests if this string ends with the specified suffix.
String str = "Java Programming";
boolean result1 = str.endsWith("Programming"); // true
boolean result2 = str.endsWith("programming"); // false,
// because case-sensitive
System.out.println("Ends with 'Programming'? " + result1);
System.out.println("Ends with 'programming'? " + result2);
These methods are beneficial for:
String comparison methods in Java are used to compare strings for equality, lexicographical ordering, or to find matches of characters or substrings within strings.
The equals() method compares the content of two strings. If the content of both strings is the same, it returns true; otherwise, it returns false. This comparison is case-sensitive.
String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";
boolean result1 = str1.equals(str2); // true
boolean result2 = str1.equals(str3); // false
System.out.println("str1 equals str2? " + result1);
System.out.println("str1 equals str3? " + result2);
The equalsIgnoreCase() method is similar to equals() but ignores case differences. It returns true if the two strings are equal, disregarding case; otherwise, it returns false.
String str1 = "Hello";
String str2 = "hello";
boolean result = str1.equalsIgnoreCase(str2); // true
System.out.println("str1 equalsIgnoreCase str2? " + result);
The compareTo() method compares two strings lexicographically (based on the Unicode value of each character in the strings). It returns:
This method is case-sensitive.
String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";
int result1 = str1.compareTo(str2); // 0
int result2 = str1.compareTo(str3); // -32 (the exact value may vary)
System.out.println("str1 compareTo str2: " + result1);
System.out.println("str1 compareTo str3: " + result2);
package ch11.l3;
public class CompateToMethod {
static String arr[] = { "Now", "is", "the", "time",
"for", "all", "good", "men", "to", "come", "to",
"the", "aid", "of", "their", "country"
};
public static void main(String[] args) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
The compareToIgnoreCase() method is similar to compareTo() but ignores case differences. It compares two strings lexicographically, ignoring case differences.
String str1 = "Hello";
String str2 = "hello";
int result = str1.compareToIgnoreCase(str2); // 0
System.out.println("str1 compareToIgnoreCase str2: " + result);
-1 is returned.indexOf(int ch): Looks for a single character.indexOf(String str): Searches for a substring.indexOf(int ch, int fromIndex): Starts the search for a character from the specified index.indexOf(String str, int fromIndex): Starts the search for a substring from the specified index.
package ch11.l3;
public class IndexOfExample {
public static void main(String[] args) {
String str = "Hello, world! Welcome to the world of Java.";
// Find the index of a character
int index1 = str.indexOf('o');
System.out.println("Index of 'o': " + index1);
// Find the index of a character, starting from a specific index
int index2 = str.indexOf('o', 5);
System.out.println("Index of 'o' after index 5: " + index2);
// Find the index of a substring
int index3 = str.indexOf("world");
System.out.println("Index of "world": " + index3);
// Find the index of a substring, starting from a specific index
int index4 = str.indexOf("world", 10);
System.out.println("Index of "world" after index 10: " + index4);
// Attempt to find an index of a character that does not exist
int index5 = str.indexOf('x');
System.out.println("Index of 'x': " + index5);
// Attempt to find an index of a substring that does not exist
int index6 = str.indexOf("Python");
System.out.println("Index of "Python": " + index6);
}
}
Index of 'o': 4
Index of 'o' after index 5: 8
Index of "world": 7
Index of "world" after index 10: 29
Index of 'x': -1
Index of "Python": -1
-1 is returned.lastIndexOf(int ch): Searches for the last occurrence of a character.lastIndexOf(String str): Searches for the last occurrence of a substring.lastIndexOf(int ch, int fromIndex): Starts the search backward from the specified index for a character.lastIndexOf(String str, int fromIndex): Starts the search backward from the specified index for a substring.
package ch11.l3;
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello, world! Welcome to the world of Java.";
// Find the last index of a character
int index1 = str.lastIndexOf('o');
System.out.println("Last index of 'o': " + index1);
// Find the last index of a character before a specific index
int index2 = str.lastIndexOf('o', 25);
System.out.println("Last index of 'o' before index 25: " + index2);
// Find the last index of a substring
int index3 = str.lastIndexOf("world");
System.out.println("Last index of "world": " + index3);
// Find the last index of a substring before a specific index
int index4 = str.lastIndexOf("world", 10);
System.out.println("Last index of "world" before index 10: " + index4);
// Attempt to find the last index of a character that does not exist
int index5 = str.lastIndexOf('x');
System.out.println("Last index of 'x': " + index5);
// Attempt to find the last index of a substring that does not exist
int index6 = str.lastIndexOf("Python");
System.out.println("Last index of "Python": " + index6);
}
}
Last index of 'o': 35
Last index of 'o' before index 25: 23
Last index of "world": 29
Last index of "world" before index 10: 7
Last index of 'x': -1
Last index of "Python": -1
The regionMatches() method in Java is used to compare a specific region inside a string with another region in another string.
regionMatches(int toffset, String other, int ooffset, int len)
regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Parameters:
toffset – the starting offset of the subregion in this string.other – the string argument.ooffset – the starting offset of the subregion in the string argument.len – the number of characters to compare.ignoreCase – if true, ignore the case when comparing characters.Returns: true if the specified subregion of this string exactly matches the specified subregion of the string argument.
package ch11.l3;
public class RegionMatchDemo {
public static void main(String[] args) {
String str1 = "I love Java programming.";
String str2 = "Java";
/* Check if the substring starting at
* index 7 in str1 matches "Java"
*/
boolean match = str1.regionMatches(7, str2, 0, str2.length());
System.out.println("Region match is: " + match);
// Output: Region match is: true
}
}
Region match is: true
In this example, the method regionMatches(int toffset, String other, int ooffset, int len) is called with the following parameters:
toffset: 7 (the starting index in str1 where the region starts)other: “Java” (the String we want to match against)ooffset: 0 (the starting index in str2 where the region starts)len: str2.length() (the number of characters to be compared)The output true indicates that the region of str1 starting at index 7 for a length of 4 characters (“Java”) matches the string str2 (“Java”).
package ch11.l3;
public class RegionMatchDemo {
public static void main(String[] args) {
String str1 = "I love JAVA programming.";
String str2 = "java";
/* Check if the substring starting at index 7
* in str1 matches "java" (case-insensitive)
*/
boolean match = str1.regionMatches(true, 7, str2, 0, str2.length());
System.out.println("Region match (case-insensitive) is: " + match);
// Output: Region match (case-insensitive) is: true
}
}
Region match (case-insensitive) is: true
ignoreCase: true (indicating that the comparison should ignore case differences)The output true indicates that the region of str1 starting at index 7 for a length of 4 characters (“JAVA”) matches str2 (“java”) when the case is ignored.
Survival kit
good
You must be logged in to submit a review.