1. Method length(): how many characters are in a string?
The length() method returns the number of characters in a string. This is not quite the same as “number of bytes” (especially if the string contains emoji or Unicode characters), but for most tasks it’s exactly what you need.
Usage example
String name = "Vasilisa";
int length = name.length();
System.out.println("Number of letters in the name: " + length); // 8
Why it’s useful
- Check whether the user entered an empty string.
- Validate minimum/maximum password length.
- Find out how many characters remain to a limit (for example, in an SMS or a tweet).
Example: check for an empty string
String input = "";
if (input.length() == 0)
{
System.out.println("The string is empty!");
}
Pro tip: to check whether a string is “empty” there is also the isEmpty() method — more on it a bit later.
Quick FAQ
- The length() method takes no arguments (the parentheses are always empty).
- If a string consists of spaces, they are counted as characters too!
- If a string is null, calling length() will result in a NullPointerException — check for null first.
2. Method substring(): extracting part of a string
The substring() method lets you get a substring — “cut” a piece by specified indices.
There are two main forms of call:
- str.substring(startIndex) — from position startIndex to the end of the string.
- str.substring(startIndex, endIndex) — from position startIndex to endIndex (NOT including the character at index endIndex).
Warning: character indexing in a string starts at 0.
Examples
Example 1: Get the first three letters of a name
String name = "Vasilisa";
String firstThree = name.substring(0, 3); // "Vas"
System.out.println(firstThree);
Example 2: Get a file extension
String fileName = "document.pdf";
int dotIndex = fileName.indexOf(".");
String extension = fileName.substring(dotIndex + 1); // "pdf"
System.out.println(extension);
Example 3: The last 4 characters of a string
String cardNumber = "1234567890123456";
String lastFour = cardNumber.substring(cardNumber.length() - 4); // "3456"
System.out.println("Last 4 digits: " + lastFour);
Details and nuances
- Invalid indices (startIndex < 0, endIndex > length, startIndex > endIndex) throw StringIndexOutOfBoundsException.
- The method always returns a new string — the original one is not modified.
- The second form (with two parameters) does not include the character at index endIndex.
String str = "abcdef";
// Indexes: 0 1 2 3 4 5
str.substring(1, 4) → "bcd" // characters with indexes 1, 2, 3
substring(start, end) works
3. Method indexOf(): searching for a character or substring
The indexOf() method finds the position (index) of the first occurrence of a given character or substring.
- If found — returns the index (starting from 0).
- If not found — returns -1.
Examples
Example 1: Find the first dot in an email
String email = "ivan.petrov@mail.com";
int dotIndex = email.indexOf('.');
System.out.println("The first dot is at position: " + dotIndex); // 4
Example 2: Find a substring
String text = "I love Java!";
int index = text.indexOf("Java");
System.out.println(index); // 7
Example 3: Find a character after a specific position
String s = "abracadabra";
int firstA = s.indexOf('a'); // 0
int secondA = s.indexOf('a', firstA + 1); // 3
System.out.println("The second 'a' is at position: " + secondA);
Details and nuances
- If the character/substring occurs multiple times, the index of the first occurrence is returned.
- To find the last occurrence, use lastIndexOf().
- Use single quotes for a character: 'a'; use double quotes for a substring: "abc".
Example: find a file extension
String fileName = "report.final.version.docx";
int lastDot = fileName.lastIndexOf('.');
String extension = fileName.substring(lastDot + 1);
System.out.println("File extension: " + extension); // "docx"
4. Method charAt(): get a character by index
The charAt(index) method returns the character at the given index.
Examples
Example 1: Check the first letter of a string
String city = "Minsk";
char first = city.charAt(0); // 'M'
System.out.println("First letter: " + first);
Example 2: Check whether a string starts with a capital letter
String word = "Java";
if (Character.isUpperCase(word.charAt(0)))
{
System.out.println("The word starts with a capital letter!");
}
Example 3: Iterate over all characters in a string
String text = "Hello";
for (int i = 0; i < text.length(); i++)
{
System.out.println("Character #" + i + ": " + text.charAt(i));
}
Details and nuances
- An out-of-range index (for example, -1 or >= length) will cause a StringIndexOutOfBoundsException.
- The method returns a value of type char, not a string.
5. Method toCharArray(): convert a string to a character array
The toCharArray() method is a simple way to convert a string to a character array (char[]). Useful for character-by-character processing, sorting, validation, etc.
Usage example:
String text = "Hello";
char[] characters = text.toCharArray();
for (char c : characters)
{
System.out.println(c);
}
// Output:
// H
// e
// l
// l
// o
Why it’s useful:
- Character processing: arrays are more convenient for per-character logic (for example, checking for anagrams).
- Compatibility: some APIs expect a char[] as an argument.
6. Method replace(): replacing substrings
The replace(CharSequence target, CharSequence replacement) method replaces all occurrences of target with replacement. It returns a new string; the original is not modified.
Usage example:
String sentence = "I love programming in Java.";
String newSentence = sentence.replace("Java", "Java 25");
System.out.println(newSentence);
// Output: I love programming in Java 25.
String email = "support@company.com";
String cleanEmail = email.replace("@", "[at]");
System.out.println(cleanEmail);
// Output: support[at]company.com
Details and nuances
- All occurrences are replaced.
- String is immutable: replace() returns a new string.
- For complex rules, use replaceAll() with a regular expression.
7. Methods trim() and strip(): removing whitespace
Both methods remove “invisible” characters at the beginning and end of a string.
- trim() — the classic method: removes spaces, tabs, line breaks, and some control characters, but not all Unicode spaces.
- strip() — the modern method: accounts for all kinds of spaces according to the Unicode standard. Preferable in new projects.
Usage example:
String s1 = " Hello, world! ";
System.out.println(s1.trim());
// Output: "Hello, world!"
String s2 = " \u2005 Java 11 \u2005 "; // \u2005 — this is a Unicode space
System.out.println("trim(): " + s2.trim());
System.out.println("strip(): " + s2.strip());
// Output:
// trim(): Java 11
// strip(): Java 11
Why it’s useful:
- Clean user input from extra spaces.
- Normalize data from files/logs before processing.
8. Practice: solve tasks
Task 1: Check password length
String password = "qwerty";
if (password.length() < 8)
{
System.out.println("Password is too short!");
}
else
{
System.out.println("Password is acceptable.");
}
Task 2: Extract the first name from a full name
String fullName = "Ivanov Ivan Ivanovich";
int firstSpace = fullName.indexOf(' ');
String name = fullName.substring(firstSpace + 1, fullName.indexOf(' ', firstSpace + 1));
System.out.println("Name: " + name); // "Ivan"
Task 3: Check that a string starts with a specific letter
String surname = "Petrov";
if (surname.charAt(0) == 'P')
{
System.out.println("The surname starts with the letter P");
}
Task 4: Get the domain from an email
String email = "vasya.pupkin@gmail.com";
int at = email.indexOf('@');
String domain = email.substring(at + 1);
System.out.println("Domain: " + domain); // "gmail.com"
Task 5: Find all occurrences of the letter 'a' in a string
String s = "abracadabra";
int pos = s.indexOf('a');
while (pos != -1)
{
System.out.println("Letter 'a' found at position: " + pos);
pos = s.indexOf('a', pos + 1); // search from the last found position
}
9. Typical mistakes when working with String methods
Error #1: Out of string bounds
Very often indices are confused and you access a non-existent character/substring.
String s = "Java";
char c = s.charAt(4); // Error! Indexes 0..3
String s = "Hello";
String sub = s.substring(3, 10); // Error! String length is 5
Error #2: Confusion about inclusive/exclusive end index
The substring(start, end) method includes the character at index start but does NOT include the character at index end.
Error #3: Expecting indexOf to return anything other than -1 when the substring is absent
Check the result before using it, especially if you then pass it to substring.
Error #4: Incorrect handling of empty strings
If a string is empty (""), calls like charAt(0) or substring(0, 1) will cause an error. Check the length first.
Error #5: Working with null strings
If a string is null, calling any method (length(), substring(), etc.) will throw a NullPointerException. Always check for null before processing.
GO TO FULL VERSION