Start learning free

LESSON 57 OF 410 · STRINGS I

String Slicing in Java

Lesson Read the full explanation

Not only we can select a single character from a string, but we can also select a sequence of consecutive characters (e.g. substring) from a string.

To achieve this, we use the substring() method like this:

string.substring(startIndex, endIndex);

This is called slicing a string. It returns the substring from startIndex to endIndex.

Here is an example:

String language = "JavaScript";
String substring = language.substring(2, 6);

System.out.println(substring); // Output: "vaSc"
System.out.println(language); // Output: "JavaScript"

The startIndex is a zero-based index at which we start extraction and the endIndex is also zero-based index before which we end the extraction.

The substring will not include the character at endIndex. You can see in our example that the character at index 2 (v) was included while the character at index 6 (r) was excluded.

Also notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring.


If you omit the endIndex, the slice() extracts to the end of the string:

String language = "JavaScript";
String substring = language.substring(4);

System.out.println(substring); // Output: "Script"

Assignment
Follow the Coding Tutorial and let's slice some strings!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · STRINGS I

    String Slicing in Java, explained

    Java String Slicing with substring(): Extract Substrings Safely

    Java’s substring() method is the primary tool for extracting parts of a string — used every day in parsing dates, processing file paths, extracting tokens from structured text, and formatting output. Unlike Python, Java has no slice syntax (s[2:6]), and unlike JavaScript’s slice(), Java’s substring() does not support negative indices. Understanding exactly what it does — and what it throws — prevents bugs before they happen.

    Visualising the Indices

    Indices in Java strings are zero-based. substring(2, 6) starts at index 2 (inclusive) and ends at index 6 (exclusive):

    String s = "JavaScript";
    //          J  a  v  a  S  c  r  i  p  t
    //          0  1  2  3  4  5  6  7  8  9
    
    System.out.println(s.substring(2, 6));   // "vaSc"   — indices 2, 3, 4, 5
    System.out.println(s.substring(4));      // "Script" — from 4 to end
    System.out.println(s.substring(0, 4));   // "Java"   — first 4 characters
    

    The Two Forms of substring()

    String s = "JavaScript";
    
    // Form 1: substring(startIndex, endIndex)
    // — startIndex inclusive, endIndex exclusive
    String part = s.substring(2, 6);
    System.out.println(part);              // "vaSc"
    
    // Form 2: substring(startIndex)
    // — extracts from startIndex to the end of the string
    String tail = s.substring(4);
    System.out.println(tail);             // "Script"
    
    // Getting last N characters (no negative indices in Java):
    int n = 6;
    String lastN = s.substring(s.length() - n);
    System.out.println(lastN);            // "Script"
    

    No Negative Indices — Use length() Instead

    Unlike Python’s s[-6:] or JavaScript’s s.slice(-6), Java does not support negative indices. To count from the end, use length():

    String s = "JavaScript";
    
    // Python: s[-6:]  → last 6 chars
    System.out.println(s.substring(s.length() - 6));     // "Script"
    
    // Python: s[:-4]  → everything except last 4
    System.out.println(s.substring(0, s.length() - 4));  // "JavaSc"
    
    // Last character:
    System.out.println(s.charAt(s.length() - 1));         // ‘t’
    

    StringIndexOutOfBoundsException: When It Throws

    Java validates your indices — unlike JavaScript, bad indices throw a StringIndexOutOfBoundsException at runtime:

    String s = "Hi";
    
    // These throw StringIndexOutOfBoundsException:
    // s.substring(-1);       — negative index
    // s.substring(0, 10);    — endIndex > length
    // s.substring(5);        — startIndex > length
    // s.substring(5, 3);     — startIndex > endIndex
    
    // Safe check before slicing:
    int start = 0, end = 10;
    if (end <= s.length() && start >= 0 && start <= end) {
        System.out.println(s.substring(start, end));
    }
    

    Dynamic Slicing with indexOf()

    The most powerful pattern: combine indexOf() with substring() to find boundaries at runtime:

    // Parse a date string "2024-03-15":
    String date = "2024-03-15";
    String year  = date.substring(0, 4);   // "2024"
    String month = date.substring(5, 7);   // "03"
    String day   = date.substring(8, 10);  // "15"
    System.out.println(year + "/" + month + "/" + day);  // "2024/03/15"
    
    // Extract domain from email:
    String email = "user@example.com";
    int atPos = email.indexOf(‘@’);
    String domain = email.substring(atPos + 1);
    System.out.println(domain);            // "example.com"
    
    // Extract a known word from a sentence:
    String sentence = "Find the word Java in this sentence.";
    int start = sentence.indexOf("Java");
    String word = sentence.substring(start, start + 4);
    System.out.println(word);             // "Java"
    

    Real-World Pattern: Parsing Structured Text

    // Extract protocol and host from a URL:
    String url = "https://example.com/path";
    int schemeEnd = url.indexOf("://");
    String protocol = url.substring(0, schemeEnd);   // "https"
    
    int hostStart = schemeEnd + 3;
    int hostEnd   = url.indexOf(‘/’, hostStart);
    String host = hostEnd == -1
        ? url.substring(hostStart)
        : url.substring(hostStart, hostEnd);          // "example.com"
    
    System.out.println(protocol);   // "https"
    System.out.println(host);       // "example.com"
    

    Key Takeaways

    • substring(start, end): start inclusive, end exclusive — same convention as Python and JavaScript.
    • No negative indices in Java — use s.length() - n to count from the end.
    • Out-of-range indices throw StringIndexOutOfBoundsException — validate before slicing in production code.
    • Combine indexOf() with substring() for dynamic text parsing.

    What to Learn Next

    With substring() solid, explore the full set of Java string methods: indexOf() and lastIndexOf() to locate positions, startsWith() and endsWith() for prefix/suffix checks, and split() to break a string into an array. For complex parsing, learn regular expressions with Pattern and Matcher. In algorithm problems, substring extraction is fundamental to sliding window, palindrome checking, and string compression problems.

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free