Extracting Information from Strings in Java
Swipe to show menu
When working with text in real applications, you rarely need the entire string — most of the time you only need a small piece of it. A name inside an email, a product inside an order message, or a specific keyword hidden in a sentence. Java gives us simple but powerful tools to pull out exactly what we need.
substring()
If you need to take a "slice" of a string based on character positions, use .substring(). It relies on zero-based indexing — counting starts from 0. It returns a new String.
Main.java
123456789101112package com.example; public class Main { public static void main(String[] args) { String order = "Large Latte with oat milk"; String drinkName = order.substring(6, 11); System.out.println(drinkName); } }
substring(6, 11) tells Java to start at index 6 (included) and stop right before index 11 (excluded) — extracting characters at positions 6 through 10, which gives us "Latte".
If you use substring(start) with only one argument, Java extracts everything from that position to the end of the string:
order.substring(6); // "Latte with oat milk"
indexOf()
If you need to find where a specific piece of text is located inside a string, use .indexOf(). Instead of cutting text, it locates it. It returns an int representing the starting index of the match.
Main.java
123456789101112package com.example; public class Main { public static void main(String[] args) { String order = "Large Latte with oat milk"; int lattePosition = order.indexOf("Latte"); System.out.println(lattePosition); } }
Java scans the string from left to right until it finds "Latte" and returns the position of its first character — 6. If the text is not found anywhere in the string, Java returns -1.
Combining Both — Real Example
This real example combines indexOf() and substring() to extract a username from an email address.
Main.java
1234567891011121314package com.example; public class Main { public static void main(String[] args) { String customerEmail = "anna.coffee@gmail.com"; int atPosition = customerEmail.indexOf("@"); String username = customerEmail.substring(0, atPosition); System.out.println(username); } }
indexOf("@") finds the position of the @ symbol, then substring(0, atPosition) extracts everything from the start of the string up to — but not including — the @. The result is "anna.coffee". Instead of hardcoding positions, we let Java locate the boundary and extract exactly what we need.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat