To return a substring of a string in Java, you can use the substring() method of the String class. This method takes two arguments: the starting index of the substring (inclusive), and the ending index of the substring (exclusive).
For example, to return a substring of a string that starts at the first character (index 0) and ends at the fifth character (index 4), you can use the following code:
String str = "Hello, world!"; String sub = str.substring(0, 5); System.out.println(sub); // Output: "Hello"
In this example, the substring() method returns the substring that starts at the first character (index 0) and ends at the fifth character (index 4), which is "Hello". The println() method is used to print the resulting substring to the console.
Note that the substring() method does not modify the original string. It simply returns a new string that contains the specified substring.
Additionally, if you only want to specify the starting index of the substring, you can use the substring() method that takes a single argument (the starting index). This version of the method will return the substring that starts at the specified index and continues to the end of the original string. For example:
String str = "Hello, world!"; String sub = str.substring(6); System.out.println(sub); // Output: "world!"
In this case, the substring() method returns the substring that starts at the seventh character (index 6) and continues to the end of the original string, which is "world!".