Code Logo

Extract with String.substring()

Published at25 Jul 2026
Java OOP Easy 0 views
Like0

Write a Java function that takes a string and two indices, and returns the substring from beginIndex (inclusive) to endIndex (exclusive) using String.substring().

String.substring() is a method that returns a new string that is a substring of the original string. The beginIndex is inclusive, and the endIndex is exclusive. If endIndex is omitted, the substring extends to the end of the string. Indices are zero-based.

In Java 7+, substring() creates a new character array instead of sharing the original's backing array (as Java 6 did). This prevents memory leaks from holding large strings but creates a new copy for each call. The method throws IndexOutOfBoundsException if the indices are invalid.

Time complexity is O(n) where n is the substring length (due to the char[] copy). Space complexity is O(n) for the new substring. The method validates that beginIndex >= 0, endIndex <= length, and beginIndex <= endIndex.

Edge cases include extracting the entire string (0, length), extracting an empty string (beginIndex == endIndex), extracting from the beginning (0, n), and extracting to the end (n, length).

Example Input & Output

Example 1
Input
"hello",2,2
Output
Explanation

Empty substring

Example 2
Input
"hello",1,4
Output
ell
Explanation

Characters 1 to 4

Example 3
Input
"hello",0,1
Output
h
Explanation

First character

Example 4
Input
"hello",0,5
Output
hello
Explanation

Full string

Example 5
Input
"hello",3,5
Output
lo
Explanation

Last two chars

Algorithm Flow

Recommendation Algorithm Flow for Extract with String.substring()
Recommendation Algorithm Flow for Extract with String.substring()

Solution Approach

class Solution {
    public String solution(String s, int start, int end) {
        return s.substring(start, end);
    }
}

Best Answers

java - Approach 1
class Solution {
    public String solution(String s, int start, int end) {
        return s.substring(start, end);
    }
}