In Java, a substring is a part of a string that can be obtained by extracting a subset of characters from the original string. The substring() method in Java is used to extract a substring from a given string.
public class Main { public static void main(String[] args) { String str = "Hello, World!"; // Get a substring from index 7 to the end String substr1 = str.substring(7); System.out.println(substr1); // Outputs: World! // Get a substring from index 0 to 5 String substr2 = str.substring(0, 5); System.out.println(substr2); // Outputs: Hello } }
Here's an example of how to use the substring() method: