Substring in Java
From an email address you want the username; from a date like "2026-11-12" you want the year; from a full name, the first name. Each time you need part of a string. substring cuts out that part for you. The only tricky detail is that the end position you give is not included, and once you see why, you'll rarely get it wrong.
Cutting Out a Piece
public class Emails {
public static void main(String[] args) {
String email = "navika.anamaneni@example.com";
int at = email.indexOf('@');
String user = email.substring(0, at);
String domain = email.substring(at + 1);
System.out.println(user);
System.out.println(domain);
String date = "2026-11-12";
System.out.println("Year " + date.substring(0, 4)
+ ", month " + date.substring(5, 7));
}
}navika.anamaneni
example.com
Year 2026, month 11How it works
indexOf('@')finds where the@is: position 16.substring(0, at)takes characters from position 0 up to but not including 16: everything before the@.substring(at + 1)takes from just after the@to the end of the string.- In the date,
substring(0, 4)gives 4 characters (positions 0 to 3), andsubstring(5, 7)gives 2.
Why the End Is Excluded
Excluding the end looks odd at first, but it makes everyday code simpler:
| Benefit | Example |
|---|---|
Length is just end - begin | substring(5, 7) has 2 characters |
| Pieces fit together with no gaps or overlaps | s.substring(0, k) + s.substring(k) always equals s |
The whole string is substring(0, s.length()) | No - 1 needed |
It matches loops like for (i = begin; i < end; i++) | Same "less than end" habit |
The Errors
Positions must stay within 0 and length(), and begin can't be after end:
Call on "Java" (length 4) | Result |
|---|---|
substring(4) | "": an empty string, which is allowed |
substring(1, 1) | "": begin equals end |
substring(2, 9) | StringIndexOutOfBoundsException: Range [2, 9) out of bounds for length 4 |
substring(3, 1) | StringIndexOutOfBoundsException: Range [3, 1) out of bounds for length 4 |
The [2, 9) in the message uses the mathematical way of writing "2 included, 9 excluded".
Common Mistakes
Off-by-one on the end. To get 4 characters from position 0, write substring(0, 4), not substring(0, 3).
Not checking indexOf for -1. Handle "not found" before cutting.
Expecting substring to change the original. Strings are immutable; use the returned value.
Practice
- Easy: From
"Srihitha Anamaneni", print the first name and the surname usingindexOf(' ')andsubstring. - Harder: Write
static String extension(String fileName)that returns the part after the last dot ("report.final.pdf"gives"pdf"), and returns""when there's no dot.
Key Takeaways
Was this tutorial helpful?