Substring Extraction :

In Java, substring extraction refers to the process of extracting a portion of a string based on specific starting and ending indices. 

This allows you to work with and manipulate specific parts of a string. Here are some important details to consider:


Using the substring() method:

  1. The substring() method is provided by the String class in Java to extract substrings.
  2. It takes one or two parameters: the starting index and the optional ending index.
  3. The starting index is inclusive, meaning the character at that index is included in the extracted substring.
  4. The ending index is exclusive, meaning the character at that index is not included in the extracted substring.

Example 1:


String message = "Hello, World!"
String substring = message.substring(7);
 System.out.println(substring); // Output: World!

In the above example, substring() is called with a single argument, the starting index 7. 

This extracts the substring starting from index 7 until the end of the string. The resulting substring is "World!".

Example 2:


String message = "Hello, World!"
String substring = message.substring(0, 5); 
System.out.println(substring); // Output: Hello

In this example, substring() is called with two arguments: the starting index 0 and the ending index 5. 

This extracts the substring starting from index 0 up to, but not including, index 5. The resulting substring is "Hello".


Substring with length:

  1. In addition to specifying the starting and ending indices, you can also extract a substring by providing the starting index and the desired length of the substring.
  2. This approach allows you to define the length of the substring directly, instead of specifying the ending index.

Example 3:


String message = "Hello, World!";
String substring = message.substring(7, 12); 
System.out.println(substring); // Output: World

In this example, substring() is called with two arguments: the starting index of 7 and the desired length of 5. 

This extracts a substring starting from index 7 and with a length of 5 characters. The resulting substring is "World".


It's important to note that when working with substring extraction, you should ensure that the specified indices are within the valid range of the original string to avoid IndexOutOfBoundsException.


Substring extraction provides a powerful tool for manipulating and analyzing specific portions of strings. 

By utilizing the substring() method in Java, you can easily extract substrings based on starting and ending indices or by specifying the starting index and the desired length. 

This allows for more fine-grained string operations and enhances the flexibility of string manipulation in your Java programs.