0% found this document useful (0 votes)
67 views

String Class

String is a sequence of characters that is immutable in Java. There are two ways to create strings: using string literals or the new keyword. String literals create only one string object in memory even if the same literal is used in multiple places. Using new creates separate string objects. The String class has many useful methods like charAt(), length(), equals(), concat() etc. to manipulate and work with strings. StringBuffer is a mutable alternative to String that allows modifying strings after creation using methods like append(), insert(), replace() etc.

Uploaded by

Prerna Gour
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

String Class

String is a sequence of characters that is immutable in Java. There are two ways to create strings: using string literals or the new keyword. String literals create only one string object in memory even if the same literal is used in multiple places. Using new creates separate string objects. The String class has many useful methods like charAt(), length(), equals(), concat() etc. to manipulate and work with strings. StringBuffer is a mutable alternative to String that allows modifying strings after creation using methods like append(), insert(), replace() etc.

Uploaded by

Prerna Gour
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

String 

is nothing but a sequence of characters, for e.g. “Hello” is a string of 5


characters. In java, string is an immutable object which means it is constant and can
cannot be changed once it has been created. In this tutorial we will learn about String
class and String methods in detail along with many other Java String tutorials.

Creating a String

There are two ways to create a String in Java

1. String literal
2. Using new keyword

String literal

In java, Strings can be created like this: Assigning a String literal to a String instance:

String str1 = "Welcome";


String str2 = "Welcome";
The problem with this approach: As I stated in the beginning that String is an object
in Java. However we have not created any string object using new keyword above.
The compiler does that task for us it creates a string object having the string literal
(that we have provided , in this case it is “Welcome”) and assigns it to the provided
string instances.
But if the object already exist in the memory it does not create a new Object rather
it assigns the same old object to the new instance, that means even though we have
two string instances above(str1 and str2) compiler only created on string object
(having the value “Welcome”) and assigned the same to both the instances. For
example there are 10 string instances that have same value, it means that in memory
there is only one object having the value and all the 10 string instances would be
pointing to the same object.
What if we want to have two different object with the same string? For that we would
need to create strings using new keyword.

Using New Keyword

As we saw above that when we tried to assign the same string object to two different
literals, compiler only created one object and made both of the literals to point the
same object. To overcome that approach we can create strings like this:

String str1 = new String("Welcome");


String str2 = new String("Welcome");
In this case compiler would create two different object in memory having the same
text.

String class function


The following methods are some of the most commonly used methods of String class.

charAt()

charAt() function returns the character located at the specified index.

String str = "studytonight";

System.out.println(str.charAt(2));

Output : u

equalsIgnoreCase()

equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case
doesn't matters with this fuction ).
String str = "java";

System.out.println(str.equalsIgnoreCase("JAVA"));

Output : true

length()

length() function returns the number of characters in a String.

String str = "Count me";

System.out.println(str.length());

Output : 8

replace()

replace() method replaces occurances of character with a specified new character.

String str = "Change me";

System.out.println(str.replace('m','M'));

Output : Change Me

substring()

substring() method returns a part of the string. substring() method has two forms,

public String substring(int begin);

public String substring(int begin, int end);

The first argument represents the starting point of the subtring. If the substring() method is called
with only one argument, the subtring returned, will contain characters from specified starting point to
the end of original string.

But, if the call to substring() method has two arguments, the second argument specify the end point
of substring.
String str = "0123456789";

System.out.println(str.substring(4));

Output : 456789

System.out.println(str.substring(4,7));

Output : 456

toLowerCase()

toLowerCase() method returns string with all uppercase characters converted to lowercase.

String str = "ABCDEF";

System.out.println(str.toLowerCase());

Output : abcdef

valueOf()

Overloaded version of valueOf() method is present in String class for all primitive data types and for
type Object.

NOTE : valueOf() function is used to convert primitive data types into Strings.

But for objects, valueOf() method calls toString() function.

toString()

toString() method returns the string representation of the object used to invoke this
method. toString() is used to represent any Java Object into a meaningful string representation. It is
declared in the Object class, hence can be overrided by any java class. (Object class is super class
of all java classes.)

public class Car {

public static void main(String args[])

{
Car c=new Car();

System.out.println(c);

public String toString()

return "This is my car object";

Output : This is my car object

Whenever we will try to print any object of class Car, its toString() function will be called. toString()
can also be used with normal string objects.

String str = "Hello World";

System.out.println(str.toString());

Output : Hello World

toString() with Concatenation

Whenever we concatenate any other primitive data type, or object of other classes with a String
object,toString() function or valueOf() function is called automatically to change the other object or
primitive type into string, for successful concatenation.

int age = 10;

String str = "He is" + age + "years old.";

In above case 10 will be automatically converted into string for concatenation


using valueOf() function.

toUpperCase()

This method returns string with all lowercase character changed to uppercase.

String str = "abcdef";


System.out.println(str.toLowerCase());

Output : ABCDEF

trim()

This method returns a string from which any leading and trailing whitespaces has been removed.

String str = " hello ";

System.out.println(str.trim());

Output : hello

Java StringBuffer class


Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer class


1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.

Important methods of StringBuffer class


1. public synchronized StringBuffer append(String s): is used to append the
specified string with this string. The append() method is overloaded like
append(char), append(boolean), append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert
the specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex,
String str): is used to replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex):  is
used to delete the string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the
capacity at least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified
position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
10. public String substring(int beginIndex):  is used to return the substring from the
specified beginIndex.
11. public String substring(int beginIndex, int endIndex):  is used to return the
substring from the specified beginIndex and endIndex.

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.

1. class A{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello ");  
4. sb.append("Java");//now original string is changed  
5. System.out.println(sb);//prints Hello Java  
6. }  
7. }  

2) StringBuffer insert() method

The insert() method inserts the given string with this string at the given position.

1. class A{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello ");  
4. sb.insert(1,"Java");//now original string is changed  
5. System.out.println(sb);//prints HJavaello  
6. }  
7. }  

3) StringBuffer replace() method


The replace() method replaces the given string from the specified beginIndex and endIndex.

1. class A{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello");  
4. sb.replace(1,3,"Java");  
5. System.out.println(sb);//prints HJavalo  
6. }  
7. }  

4) StringBuffer delete() method

The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.

1. class A{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello");  
4. sb.delete(1,3);  
5. System.out.println(sb);//prints Hlo  
6. }  
7. }  

5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.

1. class A{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer("Hello");  
4. sb.reverse();  
5. System.out.println(sb);//prints olleH  
6. }  
7. }  

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.

1. class A{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer();  
4. System.out.println(sb.capacity());//default 16  
5. sb.append("Hello");  
6. System.out.println(sb.capacity());//now 16  
7. sb.append("java is my favourite language");  
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
9. }  
10. }  

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the 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.

1. class A{  
2. public static void main(String args[]){  
3. StringBuffer sb=new StringBuffer();  
4. System.out.println(sb.capacity());//default 16  
5. sb.append("Hello");  
6. System.out.println(sb.capacity());//now 16  
7. sb.append("java is my favourite language");  
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
9. sb.ensureCapacity(10);//now no change  
10. System.out.println(sb.capacity());//now 34  
11. sb.ensureCapacity(50);//now (34*2)+2  
12. System.out.println(sb.capacity());//now 70  
13. }  
14. }  

Java StringBuilder class


Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is
available since JDK 1.5.

Important Constructors of StringBuilder class


1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified
capacity as length.
Important methods of StringBuilder class
Method Description

public StringBuilder append(String is used to append the specified string with this string. The appen
s) overloaded like append(char), append(boolean), append(int), ap
append(double) etc.

public StringBuilder insert(int is used to insert the specified string with this string at the specif
offset, String s) insert() method is overloaded like insert(int, char), insert(int, bo
int), insert(int, float), insert(int, double) etc.

public StringBuilder replace(int is used to replace the string from specified startIndex and endIn
startIndex, int endIndex, String
str)

public StringBuilder delete(int is used to delete the string from specified startIndex and endInd
startIndex, int endIndex)

public StringBuilder reverse() is used to reverse the string.

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given minimu
minimumCapacity)

public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number of cha

public String substring(int is used to return the substring from the specified beginIndex.
beginIndex)

public String substring(int is used to return the substring from the specified beginIndex an
beginIndex, int endIndex)
Java StringBuilder Examples
Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this string.

1. class A{  
2. public static void main(String args[]){  
3. StringBuilder sb=new StringBuilder("Hello ");  
4. sb.append("Java");//now original string is changed  
5. System.out.println(sb);//prints Hello Java  
6. }  
7. }  

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the given
position.

1. class A{  
2. public static void main(String args[]){  
3. StringBuilder sb=new StringBuilder("Hello ");  
4. sb.insert(1,"Java");//now original string is changed  
5. System.out.println(sb);//prints HJavaello  
6. }  
7. }  

3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified beginIndex
and endIndex.

1. class A{  
2. public static void main(String args[]){  
3. StringBuilder sb=new StringBuilder("Hello");  
4. sb.replace(1,3,"Java");  
5. System.out.println(sb);//prints HJavalo  
6. }  
7. }  

4) StringBuilder delete() method


The delete() method of StringBuilder class deletes the string from the specified beginIndex
to endIndex.

1. class A{  
2. public static void main(String args[]){  
3. StringBuilder sb=new StringBuilder("Hello");  
4. sb.delete(1,3);  
5. System.out.println(sb);//prints Hlo  
6. }  
7. }  

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.

1. class A{  
2. public static void main(String args[]){  
3. StringBuilder sb=new StringBuilder("Hello");  
4. sb.reverse();  
5. System.out.println(sb);//prints olleH  
6. }  
7. }  

6) StringBuilder capacity() method

The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder 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.

1. class A{  
2. public static void main(String args[]){  
3. StringBuilder sb=new StringBuilder();  
4. System.out.println(sb.capacity());//default 16  
5. sb.append("Hello");  
6. System.out.println(sb.capacity());//now 16  
7. sb.append("java is my favourite language");  
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
9. }  
10. }  

7) StringBuilder ensureCapacity() method

The ensureCapacity() method of StringBuilder class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the 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.

1. class A{  
2. public static void main(String args[]){  
3. StringBuilder sb=new StringBuilder();  
4. System.out.println(sb.capacity());//default 16  
5. sb.append("Hello");  
6. System.out.println(sb.capacity());//now 16  
7. sb.append("java is my favourite language");  
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
9. sb.ensureCapacity(10);//now no change  
10. System.out.println(sb.capacity());//now 34  
11. sb.ensureCapacity(50);//now (34*2)+2  
12. System.out.println(sb.capacity());//now 70  
13. }  
14. }  

Difference between String and StringBuffer


There are many differences between String and StringBuffer. A list of differences between
String and StringBuffer are given below:

No. String StringBuffer

1 String class is immutable. StringBuffer class is mu


)

2 String is slow and consumes more memory when you concat too StringBuffer is fast and
) many strings because every time it creates new instance. memory when you canc

3 String class overrides the equals() method of Object class. So you StringBuffer class doesn
) can compare the contents of two strings by equals() method. equals() method of Obj

Performance Test of String and StringBuffer


1. public class ConcatTest{  
2.     public static String concatWithString()    {  
3.         String t = "Java";  
4.         for (int i=0; i<10000; i++){  
5.             t = t + "Tpoint";  
6.         }  
7.         return t;  
8.     }  
9.     public static String concatWithStringBuffer(){  
10.         StringBuffer sb = new StringBuffer("Java");  
11.         for (int i=0; i<10000; i++){  
12.             sb.append("Tpoint");  
13.         }  
14.         return sb.toString();  
15.     }  
16.     public static void main(String[] args){  
17.         long startTime = System.currentTimeMillis();  
18.         concatWithString();  
19.         System.out.println("Time taken by Concating with String: "+
(System.currentTimeMillis()-startTime)+"ms");  
20.         startTime = System.currentTimeMillis();  
21.         concatWithStringBuffer();  
22.         System.out.println("Time taken by Concating with  StringBuffer: "+
(System.currentTimeMillis()-startTime)+"ms");  
23.     }  
24. }  
Time taken by Concating with String: 578ms
Time taken by Concating with StringBuffer: 0ms

String and StringBuffer HashCode Test


As you can see in the program given below, String returns new hashcode value when you
concat string but StringBuffer returns same.

1. public class InstanceTest{  
2.     public static void main(String args[]){  
3.         System.out.println("Hashcode test of String:");  
4.         String str="java";  
5.         System.out.println(str.hashCode());  
6.         str=str+"tpoint";  
7.         System.out.println(str.hashCode());  
8.    
9.         System.out.println("Hashcode test of StringBuffer:");  
10.         StringBuffer sb=new StringBuffer("java");  
11.         System.out.println(sb.hashCode());  
12.         sb.append("tpoint");  
13.         System.out.println(sb.hashCode());  
14.     }  
15. }  
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

You might also like