String Manipulation
String Manipulation
- String
- StringBuffer
- StringBuilder
- Def : String is an object of String class that represents a sequence of characters.
- In C/C++ programming languages, it represents an array of characters, where the last character will be the null character (\0) that represents the end of the string.
- Strings are objects in Java.
- String object is immutable in Java.
- String is not a primitive data type. It is a reference data type.
- string is fixed-length, immutable, and cannot be modified.
- string literal.
- new keyword.
- converting character arrays into strings
2. Creating String Object by new Keyword
- JVM will create the second object as a copy for literal “Hello” in string constant pool for future purposes.
- Whenever we will create a string object using the new operator, compulsory a new object will be created in the heap area and another one copy will be created in the string constant pool for further future purposes.
- For every string literal, JVM will create a string object in the string constant pool.
2.StringBuffer Class in Java
- - Java StringBuffer class is used to create mutable (modifiable) String objects.
- StringBuffer in Java is a peer class of String that provides much of the functionality of strings. It provides more flexibility than String.
- To overcome string, Java introduced another class called StringBuffer.
- Java StringBuffer represents a growable nature and mutable(change).
- StringBuffer class method is synchronized. Therefore, it is a thread-safe class but it is slower than string.
Syntax
StringBuffer sb = new StringBuffer();
3.StringBuffer Methods in Java
- append()
- capacity()
- charAt()
- delete()
- ensureCapacity()
- getChars()
- indexOf()
- insert()
- length()
- reverse() and many more.
3. Java StringBuilder Class
- Java StringBuilder class represents a mutable sequence of characters (string).
- StringBuffer is thread-safe and StringBuilder is not thread-safe.
- StringBuilder is suitable to use when no thread-safety is needed.
Syntax
StringBuilder sb = new StringBuilder();
When to Use String, StringBuffer, or StringBuilder in Java?
1. String is suitable to use when you do not want to modify the content in the string object. String is an immutable class. Once created, its content cannot be changed.
2. StringBuffer can be used when we want to perform any changes in the content and need synchronization. It can be used when you are working in multithreading environment.
3. StringBuilder can be used when you want to create a string within a single thread. It will improve the execution time and performance.
Speed:
a) String is slower than StringBuffer and StringBuilder.
b) StringBuffer is slower than StringBuilder, but it is faster than String.
c) StringBuilder is faster than string and StringBuffer.
Comments
Post a Comment