Published by: sadikshya
Published date: 17 Jun 2021
The String Buffer class is used to create a mutable string. It is the same as the String class except it is mutable and thread-safe.
A string is a data type used in programmings, such as an integer and floating-point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers.
Java Swing
In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string.
char[] ch={‘j’,’a’,’v’,’a’,’p’,’o’,’i’,’n’,’t’};
String s=new String(ch);
is same as:
String s=”javapoint”;
creating string
In java, a string is an immutable object which means it is constant and cannot be changed once it has been created. There are two ways to create a string in Java:
String literal string s = “GeeksforGeeks”;
Using new keyword string s = new String (“GeeksforGeeks”);
Examples of string
public class Example{
public static void main(String args[]){
//creating a string by java string literal
String str = “Beginnersbook”;
char arrch[]={‘h’,’e’,’l’,’l’,’o’};
//converting char array arrch[] to string str2
String str2 = new String(arrch);
//creating another java string str3 by using new keyword
String str3 = new String(“Java String Example”);
//Displaying all the three strings
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
String Handling
The basic aim of the String Handling concept is storing the string data in the main memory (RAM), manipulating the data of the String, retrieving the part of the String, etc. String Handling provides a lot of concepts that can be performed on a string such as concatenation of string, comparison of string, find the substring, etc.
String
Concatenating String
In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand.
There are 2 methods to concatenate two or more string.
– Using Concat() method
– Using + operator
1) Using concat() method
string s = “Hello”;
string str = “Java”;
string str2 = s.concat(str);
String str1 = “Hello”.concat(“Java”); //works with string literals too.
2) Using + operator
string str = “Rahul”;
string str1 = “Dravid”;
string str2 = str + str1;
string st = “Rahul”+”Dravid”;
String Comparison
String comparison can be done in 3 ways.
– Using equals() method
– Using == operator
– By CompareTo() method
Using equals() method
equals() method compares two strings for equality. Its general syntax is,
boolean equals (Object str)It compares the content of the strings. It will return true if string matches, else return false.
String s = “Hell”; String s1 = “Hello”; String s2 = “Hello”; s1.equals(s2); //true s.equals(s1) ; //false
Using == operator
== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.
String s1 = “Java”;
String s2 = “Java”;
String s3 = new string (“Java”);
test(s1 == s2) //true
test(s1 == s3) //false
By compareTo() method
int compareTo(String str)String s1 = “Abhi”;
String s2 = “Viraaj”;
String s3 = “Abhi”;
s1.compareTo(S2); //return -1 because s1 < s2
s1.compareTo(S3); //return 0 because s1 == s3
s2.compareTo(s1); //return 1 because s2 > s1
Substring()
Method substring() is used for getting a substring of a particular String.
public class SubStringExample{
public static void main(String args[]) {
String str= new String(“quick brown fox jumps over the lazy dog”);
System.out.println(“Substring starting from index 15:”);
System.out.println(str.substring(15));
System.out.println(“Substring starting from index 15 and ending at 20:”);
System.out.println(str.substring(15, 20));
}
}
Output
Substring starting from index 15:
jumps over the lazy dog
Substring starting from index 15 and ending at 20:
jump
Replace()
public class Example1{
public static void main(String args[]){
String str = new String(“Site is BeginnersBook.com”);
System.out.print(“String after replacing all ‘o’ with ‘p’ :” );
System.out.println(str.replace(‘o’, ‘p’));
System.out.print(“String after replacing all ‘i’ with ‘K’ :” );
System.out.println(str.replace(‘i’, ‘K’));
}
}
Output
A String after replacing all ‘o’ with ‘p’ :Site is BeginnersBppk.cpm
A String after replacing all ‘i‘ with ‘K’ :SKte Ks BegKnnersBook.com
ReplaceFirst()
public class Example2{
public static void main(String args[]){
String str = new String(“Bcis Notes.com”);
System.out.print(“String after replacing com with net :” );
System.out.println(str.replaceFirst(“com”, “net”));
System.out.print(“String after replacing Site name:” );
System.out.println(str.replaceFirst(“Bcis Notes(.*)”, “XYZ.com”));
}
}
Output
String after replacing com with net :Site is Bcis Notes.com
String after replacing Site name:Site is XYZ.com
public class Example3{
public static void main(String args[]){
String str = new String(“My .com site is Bcis Notes.com”);
System.out.print(“String after replacing all com with net :” );
System.out.println(str.replaceAll(“com”, “net”));
}
}
Output
String after replacing all com with net :My .net site is Bcis Notes.net
indexOf()
This method returns the index within this string of the first occurrence of the specified character or -1, if the character does not occur.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String(“Bcis Notes.com”);
System.out.print(“Found Index :” );
System.out.println(Str.indexOf( ‘o’ ));
}
}
Output
Found Index :7
lastIndexOf()
This method returns the index of the last occurrence of the character in the character sequence represented by this object that is less than or equal to fromIndex, or -1 if the character does not occur before that point.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String(“Welcome to Tutorialspoint.com”);
System.out.print(“Found Last Index :” );
System.out.println(Str.lastIndexOf( ‘o’ ));
}
}
Output
Found Last Index :27
Trim()
This method returns a copy of the string, with leading and trailing whitespace omitted.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String(” Bcis Notes.com “);
System.out.print(“Return Value :” );
System.out.println(Str.trim() );
}
}
Output
Return Value :Bcis Notes.com
ToUpperCase()
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String(“Bcis Notes.com”);
System.out.print(“Return Value :” );
System.out.println(Str.toUpperCase() );
}
}
Outout
Return Value : BCIS NOTES.COM
StringBuffer
Java StringBuffer class is used to create a mutable (modifiable) string. The StringBuffer class in java is the same as the String class except it is mutable i.e. it can be changed.
Constructor | Description |
StringBuffer() | creates an empty string buffer with the initial capacity of 16. |
StringBuffer(String str) | creates a string buffer with the specified string. |
StringBuffer(int capacity) | creates an empty string buffer with the specified capacity as length. |
StringBuffer
What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello “);
sb.append(“Java”);//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello “);
sb.insert(1,”Java”);//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.replace(1,3,”Java”);
System.out.println(sb);//prints HJavalo
}
}
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuffer 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.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append(“Hello”);
System.out.println(sb.capacity());//now 16
sb.append(“java is my favourite language”);
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}