Which of these method of class StringBuffer is used to extract a substring?

This Tutorial will cover the Java substring method. We will take a look at the Syntax, brief Introduction, and Java substring Examples:

We will be also be covering the important scenario-based examples as well the frequently asked questions that will help you in understanding this method even better.

Upon going through this Java tutorial, you will be in a position to create your own programs for extracting any substring from the main String and further perform any operation on it.

=> Take A Look At The Java Beginners Guide Here.

Which of these method of class StringBuffer is used to extract a substring?

What You Will Learn:

  • Java substring()
    • Starting Index
    • Starting And Ending Index
    • Java substring Examples
    • Frequently Asked Questions
  • Conclusion
    • Recommended Reading

Java substring()

As we all know, Java substring is nothing but a part of the main String.

For example, In a String “Software Testing”, the “Software” and “Testing” are the substrings.

This method is used to return or extract the substring from the main String. Now, for the extraction from the main String, we need to specify the starting index and the ending index in the substring() method.

This method has two different forms. The syntax of each of these forms is given below.

Syntax:

String substring(int startingIndex);
String substring(int startingIndex, int endingIndex);

In the next section, we will look closely into each of these forms.

Starting Index

In this section, we will discuss the first form of the Java substring() method. The first form returns the substring that starts at the given index and then runs through the entire String. So, whatever you mention in the starting index, it will return the entire String from that particular index.

Given below is the program in which we have demonstrated the extraction by using the first form of substring() method. We have taken an input String “Software Testing Help” and then extracted the substring from index 9.

Thus, the output will be “Testing Help”.

Note: Java String index always starts with zero.

public class substring {
	
	public static void main(String[] args) {
	
		String str = "Software testing help";
		
        /*
         * It will start from 9th index and extract 
         * the substring till the last index
         */
		System.out.println("The original String is: " +str);
		System.out.println("The substring is: " +str.substring(9));
	
	}
}

Output:

Which of these method of class StringBuffer is used to extract a substring?

Starting And Ending Index

In this section, we will talk about the second form of the method. Here, we are going to take an input String “Java String substring method” and we will try to extract the substring by using the second form which is by specifying both the starting as well as ending indices.

public class substring {
	
	public static void main(String[] args) {
	
		String str = "Java String substring method";
		
        /*
         * It will start from 12th index and extract 
         * the substring till the 21st index
         */
		System.out.println("The original String is: " +str);
		System.out.println("The substring is: " +str.substring(12,21));
	
	}
}

Output:

Which of these method of class StringBuffer is used to extract a substring?

Java substring Examples

Scenario 1: What will be the output of the substring method when the specified index is not present in the main String?

Explanation: In this scenario, we are going to take an input String “Java Programming” and we will try to specify the index as 255 and 350 for the starting and ending indexes respectively.

As we know, if the String does not have a 255 index number, then it must throw an error. By the Java predefined rules for the exception, it should throw “index out of range” exception. This is because the index we have specified in the method is out of range for the given String.

public class substring {
	
	public static void main(String[] args) {
	
		String str = "Java Programming";
		
        /*
         * It will throw an error after printing the original String.
         * The index we have specified is out of range for the 
         * main String. Hence, it will throw "String index of range"
         * exception
         */
		
		System.out.println("The original String is: " +str);
		System.out.println("The substring is: " +str.substring(255,350));
	
	}
}

Output:

Which of these method of class StringBuffer is used to extract a substring?

Scenario 2: What will be the output of this method when we provide a negative index value?

Explanation: Here, we are going to take an input String “Java substring Tutorials” and we will try to provide negative starting and ending indexes and check how the program responds.

As the Java String index starts from zero, it should not accept negative integers in the index. So the program must throw an exception.

The type of error should again be the “String index out of range” exception because the specified index is not present in the main String.

public class substring {
	
	public static void main(String[] args) {
	
		String str = "Java substring Tutorials";
		
        /*
         * It will throw an error after printing the original String.
         * The index we have specified is out of range for the 
         * main String because the String index starts from zero.
         * It does not accept any negative index value. 
         * Hence, it will throw "String index of range" exception
         */
		
		System.out.println("The original String is: " +str);
		System.out.println("The substring is: " +str.substring(-5,-10));
	
	}
}

Output:

Which of these method of class StringBuffer is used to extract a substring?

Scenario 3: What will be the output of the substring when we provide (0,0) in the starting and ending indexes?

Explanation: This is yet another very good scenario to understand the String substring() Java method. Here, we will take an input String “Saket Saurav” and try to fetch the substring starting from the zeroth index and ending on the zeroth index.

It will be interesting to see how the program responds.

As we have the starting and ending indexes as the same, it should return a blank. However, the program compiles successfully in this scenario.

It will return blank for all such values where the starting and ending indexes are the same. Be it (0,0) or (1,1) or (2,2) and so on.

public class substring {
	
	public static void main(String[] args) {
	
		String str = "Saket Saurav";
		
        /*
         * The output will be blank because of the starting and ending
         * indexes can not be the same. In such scenarios, the
         * program will return a blank value. The same is applicable
         * when you are giving the input index as (0,0) or (1,1) or (2,2).
         * and so on.
         */
		
		System.out.println("The original String is: " +str);
		System.out.println("The substring is: " +str.substring(0,0));
	
	}
}

Output:

Which of these method of class StringBuffer is used to extract a substring?

Frequently Asked Questions

Q #1) How to divide a String into substrings in Java? How to create the same String again from the substrings?

Answer: Below is the program where we have taken an input String and divided the String into substrings by specifying the starting and ending indexes.

Again we have created the same String by using the substrings with the help of String concat operator.

public class substring {
	
	public static void main(String[] args) {
	
		String str = "Saket Saurav";
		
		// created two substrings substr1 and substr2
        String substr1 = str.substring(0,6);
        String substr2 = str.substring(6,12);
        
        //Printed main String as initialized
        System.out.println(str);
        
        //Printed substr1
        System.out.println(substr1);
        
        //Printed substr2
        System.out.println(substr2);
        
        //Printed main String from two substrings
        System.out.println(substr1 +substr2 );
	
	}
}

Output:

Which of these method of class StringBuffer is used to extract a substring?

Q #2) How to find if a String is a substring of another in Java?

Answer: Below is the program where we have taken an input String “Example of the substring”. Then, we have fetched a substring and stored in a String variable “substr”. Thereafter, we have used the Java contains() method to check whether the String is a part of the main String or not.

public class substring {
	
	public static void main(String[] args) {
	
		String str = "Example of the substring";
		
		// created a substring substr
        String substr = str.substring(8,10);
 
        //Printed substring
        System.out.println(substr);
        
        /*
         * used .contains() method to check the substring (substr) is a
         * part of the main String (str) or not
         */
        
        if(str.contains(substr)) {
        	System.out.println("String is a part of the main String");
        }
        else {
        	System.out.println("String is not a part of the main String");
        }
	
	}
}

Output:

Which of these method of class StringBuffer is used to extract a substring?

Q #3) What is the return type of substring() method in Java?

Answer: As we know, the String class is Immutable and substring() method is an inbuilt method of the String class. Every time you perform an operation on the String, the subsequent String is a new String that is returned.

The same thing happens with this method as well. Every time we call the substring() method, the resultant String is a new String. Hence, the return type of this method in Java is a String.

Q #4) Is String thread-safe in Java?

Answer: Yes. Just like StringBuffer, the String is also thread-safe in Java. This means that the String can only be used by a single thread at a given point in time and it does not allow two threads using a String simultaneously.

Q #5) What is the difference between two different approaches for initializing a String?

String str1 = “ABC”;
String str2 = new String(“ABC”);

Answer: Both the lines of codes will give you the String object. Now we can list out the differences.

The first line of code will return an existing object from the String pool whereas the second line of code where the String is created with the help of a “new” operator, will always return a new object that is created in the heap memory.

Although the value “ABC” is “equal” in both the lines, it is not “==”.

Now let’s take the following program.

Here we have initialized three String variables. The first comparison is done on the basis of “==” reference comparison for str1 and str2 that returns true. This is because they have used the same existing object from the String pool.

The second comparison was done on str1 and str3 using “==” where the reference comparison differs because the String object was as a part of str3 that is created newly with the help of a “new” operator. Hence, it returned false.

The third comparison was done with the help of the “.equals()” method that compared the values contained by str1 and str3. The value of both the String variables is the same i.e. they are equals. Hence, it returned true.

public class substring {
	
	public static void main(String[] args) {
	
		String str1 = "ABC";
		String str2 = "ABC"; 
		
		/*
		 *  True because "==" works on the reference comparison and 
		 *  str1 and str2 have used the same existing object from
		 *  the String pool
		 */

		System.out.println(str1 == str2);
		
		String str3 = new String ("ABC");
		
		/*
		 *  False because str1 and str3 have not the same reference
		 *  type 
		 */
		System.out.println(str1==str3);
		
		
		/*
		 *  True because ".equals" works on comparing the value contained 
		 *  by the str1 and str3. 
		 */
		System.out.println(str1.equals(str3));

	
	}
}

Output:

Which of these method of class StringBuffer is used to extract a substring?

Conclusion

In this tutorial, we have discussed the different forms of substring() method. Also, we have included multiple scenario-based questions along with the frequently asked questions that helped you in understanding the method in detail.

Further reading =>> MySQL Substring Function

Syntax, programming examples, and detailed analysis for every scenario and concept were included here. This will surely help you in developing your own programs of substring() method and carrying out different String manipulation operations on each subsequent String.

Which of these methods of class StringBuffer is used to extract a substring from a string object Mcq?

Which of these methods of class StringBuffer is used to extract a substring from a String object? Explanation: None.

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

You can extract a substring from a String using the substring() method of the String class to this method you need to pass the start and end indexes of the required substring.

Which of these method of class string is used to extract a substring from a string object * substring () substring () substring () none of the mentioned?

The split() method of String class can be used to extract a substring from a sentence.

Which of these method of class StringBuffer is used to?

Explanation: append() method of class StringBuffer is used to concatenate the string representation to the end of invoking string.