Strings can be created using two methods
- String literal: Simply enclosing text within double quotes, like?"Hello Dinuka".
- Using the?new?keyword: Instantiating a new String object, like?new String("Hello Dinuka").
- Utilizes a string pool in memory.
- If the string already exists in the pool, the same reference is used.
- Creates a new object in the heap memory every time, regardless of whether the string exists in the pool.
- Consumes more memory compared to the string literal approach.
- Strings in Java are immutable, meaning they cannot be changed once created.
- It ensures thread safety.
- Prevents unintended modifications by other parts of the program.
- While strings are inherently immutable, you can change the reference to point to a different string.
- Declare the string variable as?final.
- Use string buffers or string builders for mutable string operations.
- String buffers are thread-safe but slower due to synchronisation.
- String builders are faster but not thread-safe.
- length(): Returns the length of the string.
- charAt(int index): Returns the character at the specified index.
- substring(int beginIndex): Returns a substring starting from the specified index.
- substring(int beginIndex, int endIndex): Returns a substring between the specified begin and end indices.
- toLowerCase(): Converts all characters in the string to lowercase.
- toUpperCase(): Converts all characters in the string to uppercase.
- indexOf(String str): Returns the index of the first occurrence of the specified substring.
- lastIndexOf(String str): Returns the index of the last occurrence of the specified substring.
- replace(char oldChar, char newChar): Replaces all occurrences of a specified character with another character.
- startsWith(String prefix): Checks if the string starts with the specified prefix.
- endsWith(String suffix): Checks if the string ends with the specified suffix.