1 Understanding String Indexing
Before we learn String methods, remember that Strings are indexed starting from 0:
Length = 11 | Valid indices: 0 to 10
2 Basic String Methods
Returns the number of characters in the String.
"Hello".length()
Returns the character at the specified index.
"Hello".charAt(1)
Returns true if the String has length 0.
"".isEmpty()
3 String Concatenation
There are multiple ways to combine Strings in Java:
Each concatenation creates a NEW String object. The original Strings are not modified!
4 Extracting Substrings
Returns substring from beginIndex to end.
"Hello World".substring(6)
Returns substring from begin to end-1.
"Hello World".substring(0, 5)
Result: "llo W" (from index 2 up to but NOT including 7)
5 String Comparison
| Method | Description | Example | Result |
|---|---|---|---|
equals(String) |
Case-sensitive comparison | "Java".equals("java") |
false |
equalsIgnoreCase(String) |
Case-insensitive comparison | "Java".equalsIgnoreCase("java") |
true |
compareTo(String) |
Lexicographic comparison | "Apple".compareTo("Banana") |
negative (-1) |
startsWith(String) |
Checks if starts with prefix | "Hello".startsWith("He") |
true |
endsWith(String) |
Checks if ends with suffix | "Hello".endsWith("lo") |
true |
contains(CharSequence) |
Checks if contains substring | "Hello".contains("ell") |
true |
Never use == to compare String content. Use == only to check if two variables reference the same object.
6 Searching in Strings
Returns first occurrence index, or -1 if not found.
"Hello".indexOf('l')
Returns last occurrence index, or -1 if not found.
"Hello".lastIndexOf('l')
7 String Transformation
Converts all characters to uppercase.
"Hello".toUpperCase()
Converts all characters to lowercase.
"Hello".toLowerCase()
Removes leading and trailing whitespace.
" Hello ".trim()
Replaces all occurrences of old with new.
"Hello".replace('l', 'p')
8 Conversion: String ↔ char[] ↔ Numbers
String to char[]
Numbers to String
String to Numbers
9 Summary: Quick Reference
| Category | Methods |
|---|---|
| Basic | length(), charAt(), isEmpty() |
| Concatenation | + operator, concat() |
| Extraction | substring() |
| Comparison | equals(), equalsIgnoreCase(), compareTo(), contains(), startsWith(), endsWith() |
| Search | indexOf(), lastIndexOf() |
| Transform | toUpperCase(), toLowerCase(), trim(), replace() |
| Conversion | toCharArray(), String.valueOf(), Integer.parseInt() |
What's Next?
In the next lesson, we'll learn about StringBuilder and StringBuffer - mutable alternatives that are much more efficient for frequent String modifications!