Java Strings and String Methods – Complete Guide with Examples
Learn everything about Java Strings, including creation, manipulation, and commonly used string methods with detailed examples for beginners and advanced learners.
Strings and String Methods in Java – Complete Detailed Tutorial
A String in Java is an object that represents a sequence of characters.
Strings are widely used in text processing, user input, file handling, and data manipulation.
1. Creating Strings in Java
1.1 Using String Literal
- Stored in String Pool
- Reuses memory if same string exists
1.2 Using new Keyword
- Stored in Heap memory
- Creates a new object every time
2. String Immutability
- Strings are immutable, meaning cannot be changed once created
- Any modification creates a new string
Example:
- Use str = str.concat(" World"); to update the string
3. Commonly Used String Methods
| MethodDescriptionExample | ||
length() | Returns length of string | "Hello".length() → 5 |
charAt(index) | Returns character at index | "Hello".charAt(1) → 'e' |
concat(str) | Concatenates string | "Hi".concat(" Java") → "Hi Java" |
equals(str) | Compares strings | "Hi".equals("Hi") → true |
equalsIgnoreCase(str) | Case-insensitive compare | "hi".equalsIgnoreCase("HI") → true |
toUpperCase() | Converts to uppercase | "hello".toUpperCase() → "HELLO" |
toLowerCase() | Converts to lowercase | "HELLO".toLowerCase() → "hello" |
trim() | Removes leading/trailing spaces | " Java ".trim() → "Java" |
substring(start, end) | Extracts substring | "Hello".substring(1,4) → "ell" |
replace(old, new) | Replaces characters | "Hello".replace('l','p') → "Heppo" |
split(regex) | Splits string into array | "a,b,c".split(",") → ["a","b","c"] |
contains(str) | Checks if string contains substring | "Hello".contains("ll") → true |
startsWith(prefix) | Checks start | "Java".startsWith("Ja") → true |
endsWith(suffix) | Checks end | "Java".endsWith("va") → true |
indexOf(ch) | Returns first index | "Hello".indexOf('l') → 2 |
lastIndexOf(ch) | Returns last index | "Hello".lastIndexOf('l') → 3 |
4. String Comparison
==operator: compares references (memory address)equals()method: compares content
5. String Concatenation
- Using
+operator:
- Using
concat()method:
6. String Conversion
- String → int
- int → String
- String → double
- String → char array
7. StringBuilder and StringBuffer
- Strings are immutable
- For mutable strings, use StringBuilder or StringBuffer
Example:
- StringBuffer → thread-safe (synchronized)
- StringBuilder → faster (non-synchronized)
8. Example Program – Strings in Java
Sample Output:
9. Summary
- String → sequence of characters, immutable
- Use methods like
length(),charAt(),substring(),replace(),split() - Compare strings with equals(), not
== - Use StringBuilder/StringBuffer for mutable strings
- Strings are essential for text processing in Java