Java String - Properties:
1. Immutable: Once a String object is created, it cannot be changed.
2. Stored in String Pool: String literals are stored in a special memory area called the String
Constant Pool.
3. Final Class: The String class is final, so it cannot be inherited.
4. Implements Serializable and Comparable: Strings can be serialized and compared
lexicographically.
5. Supports Unicode: Java Strings support Unicode, allowing a wide range of characters.
6. Backed by a char array (or byte array in newer versions).
Commonly Used Inbuilt String Methods:
1. Length and Character Access
- int length()
- char charAt(int index)
- int codePointAt(int index)
2. Comparison
- boolean equals(Object another)
- boolean equalsIgnoreCase(String another)
- int compareTo(String another)
- boolean startsWith(String prefix)
- boolean endsWith(String suffix)
3. Searching
- int indexOf(String str)
- int lastIndexOf(String str)
- boolean contains(CharSequence s)
4. Substring and Modification
- String substring(int beginIndex)
- String substring(int beginIndex, int endIndex)
- String replace(char oldChar, char newChar)
- String replaceAll(String regex, String replacement)
- String replaceFirst(String regex, String replacement)
5. Case Conversion
- String toLowerCase()
- String toUpperCase()
6. Trimming and Stripping
- String trim()
- String strip()
- String stripLeading()
- String stripTrailing()
7. Joining and Concatenation
- String concat(String str)
- String join(CharSequence delimiter, CharSequence... elements)
8. Splitting and Formatting
- String[] split(String regex)
- static String format(String format, Object... args)
9. Conversion
- char[] toCharArray()
- byte[] getBytes()
- static String valueOf(Object obj)
- static String valueOf(int i)
10. Matching and Regular Expressions
- boolean matches(String regex)
- String[] split(String regex)
- String replaceAll(String regex, String replacement)
11. Interning
- String intern()
12. Empty and Blank Check
- boolean isEmpty()
- boolean isBlank()
Example:
String s = " Hello World ";
System.out.println(s.trim()); // "Hello World"
System.out.println(s.length()); // 13
System.out.println(s.toUpperCase()); // " HELLO WORLD "
System.out.println(s.contains("World")); // true
System.out.println(s.charAt(1)); // 'H'
System.out.println(s.substring(1, 6)); // "Hell"
Explanation of s = s.replaceFirst(part, ""):
- s: Original string.
- part: The substring or regex to remove.
- "": Replacing it with an empty string (deleting it).
- replaceFirst(): Replaces only the first occurrence.
Example:
String s = "apple banana apple orange";
String part = "apple";
s = s.replaceFirst(part, "");
System.out.println(s); // Output: " banana apple orange"
Note: replaceFirst() uses regex, so special characters need to be escaped.