Java String and StringBuilder methods for fast coding
Must know method
Strings
Strings are an important data type in programming because they are used to represent text data. There are several benefits of using strings:
Human-readable: Strings are easy to understand and interpret because they consist of characters that can be read and understood by humans.
Widely used: Strings are used in many applications, from text processing to web development, making them versatile data-type.
Immutable: Strings are immutable so there is no add or remove built-in function, meaning their values cannot be changed after they are created. This makes them safe to use in multi-threaded environments, where multiple threads can access the same string without causing data corruption.
String pool: Java has a special memory area called the string pool, which is used to store frequently used strings. When a string is created, the Java runtime checks the string pool for an existing string with the same value. If a match is found, the reference to the existing string is returned, rather than creating a new string object. This optimization helps to reduce memory usage and improve performance.
1. length()
2. charAt()
3. substring()
4. concat(str) or +
5.1 equals(str) or ==
5.2 compareTo(str2)
6. startsWith(String prefix)
7. endsWith(String suffix)
8. split(String regex)
StringBuilder
StringBuilder
is a class in Java that is used to create mutable (modifiable) string. Unlike the String
class, which creates an immutable string, the StringBuilder
class provides several methods to modify the contents of a string, such as append()
, insert()
, delete()
, etc.
StringBuilder
is particularly useful when you need to perform a large number of string operations because it is more efficient than creating and concatenating many String
objects. The StringBuilder
class uses a dynamic array to store characters, so its capacity can automatically expand as you add more characters to it.
In summary, StringBuilder
is in Java to provide a mutable string representation, which is more efficient for concatenating or modifying string values, compared to the String
class.
1. append()
2.1 delete(start:2 (inclu.), end: 4 (exclu.) )
2.2 deleteCharAt(3)
3.1 insert(int offset, boolean b)
3.2 insert(int offset, char c)
3.3 insert(int offset, char[] str, int offset, int len)
3.4 insert(int dstOffset, CharSequence s)
4. charAt
5. indexOf
6. substring
7. replace(int start, int end, String str)
7.1 sb.setCharAt(4, 'X');
8. capacity()
9. ensureCapacity(int minimumCapacity)