Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Exploring Methods of String in Java: Part 1

In this lesson, you will learn

  • String Query Methods
  • String Comparison Methods
  • String Search Methods

 

Working with String Methods

Here’s an overview organized into categories such as query, comparison, and searching of a String.

1. String ‘Query’ Methods

The following are the String query methods.

length(), charAt(), toCharArray(), getChars(), substring(), isEmpty(), contains(), endsWith(), startWidth().

 

1.1. length()

The length() method of the String class returns the number of characters contained in the string.

Syntax

public int length()

 

Example: length() Method

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);
    }
}

Output

The length of the string is: 13

 

1.2. charAt(int index)

Returns the character at the specified index of the string.

Syntax

char charAt(int where)

Here, where is the index of the character that you want to obtain. The value of where must be nonnegative

 

Example

String str = "Hello, World!";
char ch = str.charAt(1); // 'e'

 

1.3. toCharArray()

Converts the string to a new character array.

Syntax

char[ ] toCharArray( )

It returns an array of characters for the entire string.

 

Example

String str = "Hello, World!";
char[] chars = str.toCharArray(); 
// ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

 

1.4. getChars() Method

Extract more than one character into the destination character array at a time.

Syntax

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.

 

Example

String str = "Hello, World!";
char[] dst = new char[7];
str.getChars(0, 7, dst, 0); 
// dst contains ['H', 'e', 'l', 'l', 'o', ',', ' ']

 

1.5. substring( )

Returns a new string that is a substring of this string. It has 2 forms

Syntax

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.

Syntax

String substring(int startIndex, int endIndex)

The substring begins at the specified beginIndex and extends to the character at index endIndex-1.

 

Example

String str = "Hello, World!";
String sub1 = str.substring(7); // "World!"
String sub2 = str.substring(0, 5); // "Hello"

 

1.6. isEmpty()

  • Description: Checks if a string is empty, meaning it has a length of 0.
  • Returns: true if the string has a length of 0, otherwise false.

Example

String str1 = "";
System.out.println(str1.isEmpty()); // true

String str2 = "Hello";
System.out.println(str2.isEmpty()); // false

 

1.7. contains(CharSequence s)

  • Description: Checks if the string contains the specified sequence of char values.
  • Parameters: CharSequence s – the sequence to search for.
  • Returns: true if the sequence of char values is found, otherwise false.

Example

String sentence = "Hello, World!";
System.out.println(sentence.contains("World")); // true
System.out.println(sentence.contains("world")); // false (case-sensitive)

 

 

1.8 startsWith( ) and endsWith( )

In Java, the startsWith() and endsWith() methods are used to check if a string starts or ends with a specified prefix or suffix, respectively.

boolean startsWith() Method

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.

Example

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);

 

boolean endsWith() Method

The endsWith() method tests if this string ends with the specified suffix.

Example

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:

  • Checking file paths or URLs for specific extensions or protocols.
  • Validating user inputs, such as ensuring an email address ends with a specific domain.
  • Implementing conditional logic based on string patterns, such as routing actions or processing commands that start with certain keywords.

 

2. String Comparison Methods

String comparison methods in Java are used to compare strings for equality, lexicographical ordering, or to find matches of characters or substrings within strings.

 

2.1. equals(Object anObject)

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.

Example

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);

 

2.2. equalsIgnoreCase() Method

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);

 

2.3. compareTo() Method

The compareTo() method compares two strings lexicographically (based on the Unicode value of each character in the strings). It returns:

  • 0 if the strings are equal,
  • A value less than 0 if the calling string is lexicographically less than the argument string,
  • A value greater than 0 if the calling string is lexicographically greater than the argument string.

This method is case-sensitive.

Example

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);

 

Example: compareTo(): Sorting a String

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]);
		}
	}
}

Output

Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to

 

2.4. compareToIgnoreCase() Method

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);

 

3. String ‘Search’ Methods

 

3.1. indexOf(int ch) and indexOf(String str)

  • Description: Returns the index within the string of the first occurrence of the specified character or substring. If the character or substring is not found, then -1 is returned.
  • Overloads:
    • 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.

 

Example

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);
    }
}

Output

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

 

3.2. lastIndexOf(int ch) and lastIndexOf(String str)

  • Description: Returns the index within the string of the last occurrence of the specified character or substring. If the character or substring is not found, then -1 is returned.
  • Overloads:
    • 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.

 

Example

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);
    }
}

Output

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

 

3.3. boolean regionMatches() method

The regionMatches() method in Java is used to compare a specific region inside a string with another region in another string.

Methods:

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.

 

Example: regionMatches()

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
	}
}

Output

Region match is: true

Explanation

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”).

 

regionMatches(): Case-Insensitive Usage

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
	}
}

Output

Region match (case-insensitive) is: true

Explanatiom

  • 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.

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 2 reviews)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

05/04/2025

Survival kit

24/03/2025

good

 

 

Submit a Review