Which of these method of class string is used to extract a substring from a string object in Java?

Java String substring() method returns the substring of this string. This method always returns a new string and the original string remains unchanged because String is immutable in Java.

Java String substring() Methods

Which of these method of class string is used to extract a substring from a string object in Java?
Java String substring method is overloaded and has two variants.

  1. substring(int beginIndex): This method returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
  2. substring(int beginIndex, int endIndex): The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is (endIndex - beginIndex).

String substring() Method Important Points

  1. Both the string substring methods can throw IndexOutOfBoundsException if any of the below conditions met.
    • if the beginIndex is negative
    • endIndex is larger than the length of this String object
    • beginIndex is larger than endIndex
  2. beginIndex is inclusive and endIndex is exclusive in both substring methods.

Java String substring() Example

Here is a simple program for the substring in java.

package com.journaldev.util;

public class StringSubstringExample {

	public static void main(String[] args) {
		String str = "www.journaldev.com";
		System.out.println("Last 4 char String: " + str.substring(str.length() - 4));
		System.out.println("First 4 char String: " + str.substring(0, 4));
		System.out.println("website name: " + str.substring(4, 14));
	}
}

Output of the above substring example program is:

Last 4 char String: .com
First 4 char String: www.
website name: journaldev

Checking Palindrome using substring() Method

We can use the substring() method to check if a String is a palindrome or not.

package com.journaldev.util;

public class StringPalindromeTest {
	public static void main(String[] args) {
		System.out.println(checkPalindrome("abcba"));
		System.out.println(checkPalindrome("XYyx"));
		System.out.println(checkPalindrome("871232178"));
		System.out.println(checkPalindrome("CCCCC"));
	}

	private static boolean checkPalindrome(String str) {
		if (str == null)
			return false;
		if (str.length() <= 1) {
			return true;
		}
		String first = str.substring(0, 1);
		String last = str.substring(str.length() - 1);
		if (!first.equals(last))
			return false;
		else
			return checkPalindrome(str.substring(1, str.length() - 1));
	}
}

Here we are checking if the first letter and the last letter is the same or not. If they are not the same, return false. Otherwise, call the method again recursively passing the substring with the first and last letter removed.

You can checkout more string examples from our GitHub Repository.

Reference: Oracle API Doc

String is one of the widely used java classes. The Java String class is used to represent the character strings. All String literals in Java programs are implemented as instance of the String Class. Strings are constants and their values cannot be changed after they created. Java String objects are immutable and they can be shared. The String Class includes several methods to edit the content of string.

Nội dung chính Show

  • Exception Throws
  • Internal implementation substring(int beginIndex)
  • Internal implementation substring(int beginIndex, int endIndex)
  • Java String substring() method example
  • Java String substring() Method Example 2
  • Applications of substring() Method
  • Which methods are used to extract the characters from string?
  • Which method is used to extract a single character from a string in Java?
  • Which of the following method extracts a part of a string from a string object?
  • Which method is used to extract a single character at an index?

Creating a String Object:

A String object can be created as

String Str=”Car Insurance”;

The string object can also be created using the new operator as

String str= new String(“Car Insurance”);

Java provides a special character plus (+) to concatenate strings. The plus operator is the only operator which is overloaded in java. String concatenation is implemented through the String Builder of String Buffer class and their append method.

Examples of Java String Class:

1. Finding the length of the string

The length() method can be used to find the length of the string.

String str = "Car insurance"
System.out.println(str.length());

2. Comparing strings

The equals() method is used to comapre two strings.

String str = "car finance";

if ( str.equals("car loan") )
{
System.out.println("Strings are equal");
}
else
{
System.out.println("Strings are not equal");
}

3. Comparing strings by ignoring case

The equalsIgnoreCase() method is used to compare two strings by ignoring the case.

String str = "insurance";

if ( str.equalsIgnoreCase("INSURANCE") )
{
System.out.println("insurance strings are equal");
}
else
{
System.out.println("insurance Strings are not equal");
}

4. Finding which string is greater

The CompareTo() method compares two strings to find which string is alphabetically greater.

String str = "car finance";

if ( str.CompareTo("auto finance") > 0)
{
System.out.println("car finance string is alphabetically greater");
}
else
{
System.out.println("car finance string is alphabetically lesser");
}

5. Finding which string is greater while ignoring the case.

The compareToIgnoreCase() method is same as the CompareTo() method except that it ignores case while comparing.

String str = "car finance";

if ( str.compareToIgnoreCase("CAR finance") = 0)
{
System.out.println("strings are alphabetically same");
}
else
{
System.out.println("strings are alphabetically not same");
}

6. Position of a string in another string.

The indexOf() method is used to find the position of a string in another string.

String str= "car insurance";
System.out.println( str.indexOf("car") );

7. Extract single character from a string.

The CharAt() method is used to extract a single character by specifying the position of the character.

String str = "Auto Finance";
System.out.println( str.charAt(5) );

8. Extracting part of a string.

The substring() is used to method part of a string by specifying the start position and end position.

String str = "Car Finance";
System.out.println( str.substring(1,3));

9. Hash code of a string.

The hashCode() method is used to get the hash code of a string.

String str = "Auto Insurance";
System.out.println(str.hashCode());

10. replacing characters in a string.

The replace() method is used to replace a character in a string with new character.

string str = "Auto Loan";
System.out.println(str.replace("A", "L"));

11. Converting a string to upper case.

The toUpperCase() method is used to convert a string to upper case letters.

String str = "Cheap Car Insurance";
System.out.println(str.toUpperCase());

12. Converting a string to lower case.

The toLowerCase() method is used to covert a string to lower case letters.

String str = "Insurance Quote";
System.out.println(str.toLowerCase());

Recommended Reading:


Java HashMap Class Example

If you like this article, then please share it or click on the google +1 button.

About Us

McqMate.com is an educational platform, Which is developed BY STUDENTS, FOR STUDENTS, The only objective of our platform is to assist fellow students in preparing for exams and in their Studies throughout their Academic career.

what we offer ?

» We provide you study material i.e. PDF's for offline use.
» We take free online Practice/Mock test for exam preparation.
» Each MCQ is open for further discussion on discussion page.
» All the services offered by McqMate are free.

The Java String class substring() method returns a part of the string.

We pass beginIndex and endIndex number position in the Java substring method where beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the endIndex starts from 1.

There are two types of substring methods in Java string.

Signature

If we don't specify endIndex, the method will return all the characters from startIndex.

Parameters

startIndex : starting index is inclusive

endIndex : ending index is exclusive

Returns

specified string

Exception Throws

StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.

  • if the start index is negative value
  • end index is lower than starting index.
  • Either starting or ending index is greater than the total number of characters present in the string.

Internal implementation substring(int beginIndex)

Internal implementation substring(int beginIndex, int endIndex)

Java String substring() method example

FileName: SubstringExample.java

Test it Now

Output:

Java String substring() Method Example 2

FileName: SubstringExample2.java

Output:

Javatpoint
point
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 15, length 10

Applications of substring() Method

1) The substring() method can be used to do some prefix or suffix extraction. For example, we can have a list of names, and it is required to filter out names with surname as "singh". The following program shows the same.

FileName: SubstringExample3.java

Output:

Yuvraj Singh
Harbhajan Singh
Gurjit Singh
Sandeep Singh
Milkha Singh

2) The substring() method can also be used to check whether a string is a palindrome or not.

FileName: SubstringExample4.java

Output:

madam is a palindrome.
rock is not a palindrome.
eye is a palindrome.
noon is a palindrome.
kill is not a palindrome.

Which methods are used to extract the characters from string?

The String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf() . The indexOf() methods search forward from the beginning of the string, and the lastIndexOf() methods search backward from the end of the string.

Which method is used to extract a single character from a string in Java?

charAt() method: Get the string and the index. Get the specific character using String. charAt(index) method.

Which of the following method extracts a part of a string from a string object?

You can extract a substring from a string using the slice() method. You pass it: the index at which to start extracting.

Which method is used to extract a single character at an index?

Use the charAt method to get a character at a particular index.

Which methods of class String is used to extract a substring from a String object?

You can extract a substring from a string using the slice() method.

Which of these method of class String is used to extract a substring from a String object in Java a substring () b substring ()?

In other words, substring is a subset of another String. Java String class provides the built-in substring() method that extract a substring from the given string by using the index values passed as an argument. In case of substring() method startIndex is inclusive and endIndex is exclusive.

Which of this method of class 10th is used to extract a substring from a String object?

The substr() method extracts a part of a string.

Which of these methods of class String is used to obtain length of String object?

One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.