Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

23-Java String

The document provides an overview of the Java String class, explaining how to create string objects, their immutability, and methods for comparison and manipulation. It also introduces the StringBuffer class, highlighting its mutability and various methods for modifying strings. Key concepts include string literals, the string constant pool, and methods like append, insert, replace, and reverse in the StringBuffer class.

Uploaded by

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

23-Java String

The document provides an overview of the Java String class, explaining how to create string objects, their immutability, and methods for comparison and manipulation. It also introduces the StringBuffer class, highlighting its mutability and various methods for modifying strings. Key concepts include string literals, the string constant pool, and methods like append, insert, replace, and reverse in the StringBuffer class.

Uploaded by

TARINI MISHRA
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Java String class

In java, string is basically an object that represents sequence of char values. An array of characters
works same as java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};

String s=new String(ch);

String s="silicon";

The java.lang.String class implements Serializable, Comparable and CharSequence


interfaces.

How to create String object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

Note: String objects are stored in a special memory area known as string constant pool.

String s1="Welcome";

String s2="Welcome";//will not create new instance

Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned.
2) By new keyword

String s=new String("Welcome");//creates two objects and one reference variable

JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome"
will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Immutable String
In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable.

Once string object is created its data or state can't be changed but a new string object is
created.

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat("Tendulkar");//concat() method appends the string at the
end
System.out.println(s);//will print Sachin because strings are
immutable objects
}
}

Will work properly with

s= s.concat(" Tendulkar");

Java String compare


There are three ways to compare string in java:

1. By equals() method
2. By = = operator
3. By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string.

It compares values of string for equality.

String class provides two methods:

 public boolean equals(Object another) compares this string to the specified object.
 public boolean equalsIgnoreCase(String another) compares this String to another
string, ignoring case.

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}

2) String compare by == operator


class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to
same instance)
System.out.println(s1==s3);//false(because s3 refers to
instance created in nonpool)
}
}

3) String compare by compareTo() method

Suppose s1 and s2 are two string variables. If:

 s1 == s2 :0
 s1 > s2 :positive value
 s1 < s2 :negative value

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Sourav";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//14(because s1>s3)
System.out.println(s3.compareTo(s1));//-14(because s3 < s1 )
}
}
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string.

In case of substring startIndex is inclusive and endIndex is exclusive.

Note: Index starts from 0.

String s="hello";

System.out.println(s.substring(0,2));//he

0 points to “h” but 2 points to “e”

class Teststringcomparison1{
public static void main(String args[]){
String s="Sachin Tendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}

Java String class methods


toUpperCase() and toLowerCase() method

String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin

trim() method

The string trim() method eliminates white spaces before and after string.

String s=" Sachin ";


System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin

length() method
String s="Sachin";
System.out.println(s.length());//6

replace() method
String s1="Kava is a programming language. Kava is a platform. Kava is
an Island.";
String replaceString=s1.replace("Kava","Java");//replaces all
occurrences of "Kava" to "Java"
System.out.println(replaceString);
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.

String StringBuffer
String class is immutable. StringBuffer class is mutable.
StringBuffer is fast and consumes
String is slow and consumes more memory when you
less memory when you cancat
concat too many strings because every time it creates
strings.
new instance.

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

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.

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

class A{
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
}
}

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

class A{
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
}
}

replace() method

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

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

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

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

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

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

You might also like