Question
I want to split a string in Java using a delimiter. For example, I want to split the string "004-034556" into two separate strings using "-" as the delimiter:
String part1 = "004";
String part2 = "034556";
In other words, the first result should contain the characters before '-', and the second result should contain the characters after '-'.
I also want to check whether the string contains the delimiter '-' before splitting.
Short Answer
By the end of this page, you will understand how to split a string in Java using a delimiter, how String.split() works, how to check whether a delimiter exists with contains() or indexOf(), and how to safely handle cases where the delimiter is missing or appears multiple times.
Concept
In Java, strings are instances of the String class, which provides built-in methods for searching and dividing text.
The main method used to split text is:
split()
It breaks a string into smaller pieces based on a separator, also called a delimiter.
For example:
String value = "004-034556";
String[] parts = value.split("-");
This produces an array containing:
parts[0]→"004"parts[1]→"034556"
This matters because splitting strings is very common in real programs. Developers use it when working with:
- CSV data
- IDs like
user-123 - file paths
- API responses
- configuration values
- logs and structured text
A related concept is checking whether the delimiter exists before splitting. In Java, you can do that with:
value.contains("-")
or:
Mental Model
Think of a string like a sentence written on a strip of paper, and the delimiter is a cut mark.
If the paper looks like this:
004-034556
then - is the place where you cut it into pieces:
- left side:
004 - right side:
034556
Before cutting, you may want to check whether the cut mark exists at all. If there is no -, there is nothing to split.
So the process is:
- Look for the cut mark.
- If it exists, split the text.
- Read the pieces from the result array.
Syntax and Examples
Basic syntax
String[] parts = text.split("-");
textis the original string"-"is the delimiter- the result is a
String[]array
Example: split into two parts
String value = "004-034556";
String[] parts = value.split("-");
String part1 = parts[0];
String part2 = parts[1];
System.out.println(part1); // 004
System.out.println(part2); // 034556
This works because the string contains one -, so the split produces exactly two parts.
Example: check before splitting
String value = "004-034556";
if (value.contains("-")) {
String[] parts = value.split();
System.out.println( + parts[]);
System.out.println( + parts[]);
} {
System.out.println();
}
Step by Step Execution
Consider this code:
String value = "004-034556";
if (value.contains("-")) {
String[] parts = value.split("-");
String part1 = parts[0];
String part2 = parts[1];
System.out.println(part1);
System.out.println(part2);
}
Step-by-step
valueis assigned the text"004-034556".value.contains("-")checks whether-exists in the string.- Since
-is present, theifblock runs. value.split("-")cuts the string at the dash.- Java creates a
String[]array with two values:- index
0="004" - index
1=
- index
Real World Use Cases
Splitting strings by delimiters appears everywhere in Java programs.
Common examples
-
User input parsing
- Input like
name:Johncan be split into key and value.
- Input like
-
Product or account codes
004-034556can be split into a category code and item number.
-
CSV and text file processing
- A line like
Alice,24,Londoncan be split by,.
- A line like
-
Log processing
- A log entry like
ERROR|Database unavailablecan be split into level and message.
- A log entry like
-
Configuration strings
- A value like
host=localhostcan be split into setting name and setting value.
- A value like
-
URL or route parsing
- Paths or slugs often need to be divided into segments.
In all of these cases, checking whether the delimiter exists first helps make the code more reliable.
Real Codebase Usage
In real projects, developers usually do more than just call split().
Common patterns
Guard clause before splitting
if (!value.contains("-")) {
return;
}
This exits early if the input is not in the expected format.
Validation before using array indexes
String[] parts = value.split("-");
if (parts.length == 2) {
String left = parts[0];
String right = parts[1];
}
This prevents ArrayIndexOutOfBoundsException.
Split only once for structured values
String[] parts = value.split("-", 2);
This is common when the second part may contain the delimiter again.
Trimming spaces after splitting
String ;
String[] parts = value.split();
parts[].trim();
parts[].trim();
Common Mistakes
1. Assuming the delimiter always exists
Broken code:
String value = "004034556";
String[] parts = value.split("-");
String part2 = parts[1];
Problem:
- If there is no
-,partswill only have one element. - Accessing
parts[1]throwsArrayIndexOutOfBoundsException.
Fix:
if (value.contains("-")) {
String[] parts = value.split("-");
if (parts.length >= 2) {
String part2 = parts[1];
}
}
2. Forgetting that split() returns an array
Broken code:
String part value.split();
Comparisons
split() vs indexOf() + substring()
| Approach | Best for | Pros | Cons |
|---|---|---|---|
split("-") | General splitting into multiple parts | Short and easy to read | Uses regex, returns an array |
indexOf('-') + substring() | Splitting around one known delimiter | Explicit control, good for two parts | More manual code |
contains() vs indexOf()
| Method | Returns | Good when |
|---|
Cheat Sheet
Quick reference
Check if delimiter exists
value.contains("-")
or
value.indexOf('-') != -1
Split by delimiter
String[] parts = value.split("-");
Access parts
String part1 = parts[0];
String part2 = parts[1];
Safer version
if (value.contains("-")) {
String[] parts = value.split("-");
if (parts.length >= 2) {
String part1 = parts[0];
String part2 = parts[1];
}
}
Split only once
FAQ
How do I split a string by - in Java?
Use split("-"):
String[] parts = value.split("-");
How can I check if a string contains a dash in Java?
Use either:
value.contains("-")
or:
value.indexOf('-') != -1
What happens if split() does not find the delimiter?
It returns an array with one element: the original string.
Why does split() return an array?
Because a string may be split into many parts, not just two.
Should I use split() or substring() in Java?
Use split() for simple delimiter-based splitting. Use indexOf() and substring() when you want precise control over one split point.
Can I split a string into only two parts?
Mini Project
Description
Build a small Java program that reads a code like 004-034556, checks whether it contains a dash, and then prints the left and right parts separately. This demonstrates safe string parsing, validation, and basic array handling.
Goal
Create a Java program that safely splits a string by - and handles invalid input gracefully.
Requirements
[
"Create a string variable containing a code such as 004-034556.",
"Check whether the string contains the - delimiter before splitting.",
"If the delimiter exists, print the part before and after the dash.",
"If the delimiter does not exist, print a helpful error message.",
"Use Java string methods only."
]
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.