What is string and StringBuffer class?
String is an immutable class and its object can't be modified after it is created. String buffer is mutable classes which can be used to do operation on string object.
Constructor in Java
Whenever we use new keyword to create an instance of a class, the constructor is invoked and the object of the class is returned. Since constructor can only return the object to class, it’s implicitly done by java runtime and we are not supposed to add a return type to it. If we add a return type to a constructor, then it will become a method of the class.
String Character Extraction Methods
charAt()
getChars()
getBytes()
toCharArray()
String is a sequence of characters. In Java, objects of String are immutable which means they are constant and cannot be changed once created.
Using String.equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.
String Modifying Methods Overview
As we know that objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use a String method that constructs a new copy of the string with your modifications complete. A sampling of these methods are described in this post.
In this post, we will discuss below methods for modifying a String objects.
substring()
concat()
replace()
replaceAll()
replaceFirst()
trim()
Java String valueOf()
The valueOf() method returns the string representation of the argument passed.
class Main {
public static void main(String[] args) {
double interest = 923.234d;
// convert double to string
System.out.println(String.valueOf(interest));
}
}
// Output: 923.234
String Buffer operations
The StringBuffer class is used for storing the mutable sequence of different datatypes which means we can update the sequence of the StringBuffer class very easily and efficiently without creating a new sequence in memory.
1) append() method
The append() method concatenates the given argument with this string.
2) insert() method
The insert() method inserts the given string with this string at the given position.
3) replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex-1.
4) delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex-1.
5) reverse() method
The reverse() method of StringBuilder class reverses the current string.
6) capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.
Post a Comment
0 Comments