0% found this document useful (0 votes)
36 views83 pages

Java String Handling and Operations

java String Handling

Uploaded by

Gautam Arvind
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views83 pages

Java String Handling and Operations

java String Handling

Uploaded by

Gautam Arvind
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

String Handling

Introduction
• String is probably the most commonly used class
in java library.
• String class is encapsulated
under [Link].
• In java, every string that you create is actually an
object of type String.
• One important thing to notice about string object
is that string objects are immutable that means
once a string object is created it cannot be altered.
String
• 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);
• is same as:
• String s="javatpoint";
• Java String class provides a lot of methods to
perform operations on string such as
compare(), concat(), equals(), split(), length(),
replace(), compareTo(), intern(), substring()
etc.
• The [Link] class
implements Serializable, Comparable and Char
Sequence interfaces
CharSequence Interface
• The CharSequence interface is used to
represent sequence of characters. It is
implemented by String, StringBuffer and
StringBuilder classes. It means, we can create
string in java by using these 3 classes.
• The java String is immutable i.e. it cannot be
changed. Whenever we change any string, a
new instance is created. For mutable string,
you can use StringBuffer and StringBuilder
classes.
What is String in java
• Generally, string is a sequence of characters.
But in java, string is an object that represents
a sequence of characters. The [Link]
class is used to create string object.
• 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";
• 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. If string doesn't exist in the
pool, a new string instance is created and placed in
the pool. For example:
• String s1="Welcome";
• String s2="Welcome";//
will not create new instance
• In the above example only one object will be
created. Firstly JVM will not find any string
object with the value "Welcome" in string
constant pool, so it will create a new object.
After that it will find the string with the value
"Welcome" in the pool, it will not create new
object but will return the reference to the
same instance.
Why java uses concept of string literal?
• To make Java more memory efficient (because
no new objects are created if it exists already
in string constant pool).
2) By new keyword
• String s=new String("Welcome");//
creates two objects and one reference variabl
e
• In such case, 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).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//
creating java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}}
Output:-
• java
• strings
• example
Immutable String in Java
• 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.
Example:-
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
[Link](" Tendulkar");//
concat() method appends the string at the end
[Link](s);//
will print Sachin because strings are immutable objects
}
}
• Output:Sachin
• Here Sachin is not changed but a new object is
created with sachintendulkar. That is why
string is known as immutable.
• As you can see in the figure that two objects
are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".
• But if we explicitely assign it to the reference
variable, it will refer to "Sachin Tendulkar"
object.
• For example:
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=[Link](" Tendulkar");
[Link](s);
}
}
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar".
Please notice that still sachin object is not
modified.
Why string objects are immutable in java?

• Because java uses the concept of string


[Link] there are 5 reference
variables,all referes to one object "sachin".If
one reference variable changes the value of
the object, it will be affected to all the
reference variables. That is why string objects
are immutable in java.
Java String compare
• We can compare string in java on the basis of
content and reference.
• It is used in authentication (by equals()
method), sorting (by compareTo()
method), reference matching (by == operator)
etc.
• 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.
Example:-(equals())
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
[Link]([Link](s2));//true
[Link]([Link](s3));//true
[Link]([Link](s4));//false
}
}
• Output:
• true
• true
• false
Example:-(equalsIgnorecase)
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";

[Link]([Link](s2));//false
[Link]([Link](s3));//true
}
}
Output:
false
true
2) String compare by == operator
• The = = operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
[Link](s1==s2);//true (because both refer to same instance)
[Link](s1==s3);//
false(because s3 refers to nstance created in nonpool)
}
}
• Output:
• true
• false
3) String compare by compareTo() method

• The String compareTo() method compares


values lexicographically and returns an integer
value that describes if first string is less than,
equal to or greater than second string.
• Suppose s1 and s2 are two string variables. If:
• s1 == s2 :0
• s1 > s2 :positive value
• s1 < s2 :negative value
Example:-
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}
}
• Output:0
• 1
• -1
String Concatenation in Java
• In java, string concatenation forms a new
string that is the combination of multiple
strings. There are two ways to concat string in
java:
• By + (string concatenation) operator
• By concat() method
1) String Concatenation by + (string concatenation) operator

• Java string concatenation operator (+) is used


to add strings. For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
[Link](s);//Sachin Tendulkar
}
}
• Output:Sachin Tendulkar
2) String Concatenation by concat() method
• The String concat() method concatenates the
specified string to the end of current string.
• Syntax:public String concat(String another)
Example:-
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);//Sachin Tendulkar
}
}
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.
• You can get substring from the given string object by one
of the two methods:
• public String substring(int startIndex): This method
returns new String object containing the substring of the
given string from specified startIndex (inclusive).
• public String substring(int startIndex, int endIndex): This
method returns new String object containing the
substring of the given string from specified startIndex to
endIndex.
• In case of string:
• startIndex: inclusive
• endIndex: exclusive
• Eg:-
• String s="hello";
• [Link]([Link](0,2));//he
• In the above substring, 0 points to h but 2
points to e (because end index is exclusive).
Example of java substring
public class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
[Link]([Link](6));//Tendulkar
[Link]([Link](0,6));//Sachin
}
}
Output:-
Tendulkar
Sachin
Java String class methods
• The [Link] class provides a lot of
methods to work on string. By the help of
these methods, we can perform operations on
string such as trimming, concatenating,
converting, comparing, replacing strings etc.
• Java String is a powerful concept because
everything is treated as a string if you submit
any form in window based, web based or
mobile application.
Java String toUpperCase() and toLowerCase() method

• The java string toUpperCase() method converts


this string into uppercase letter and string
toLowerCase() method into lowercase letter.
String s="Sachin";
[Link]([Link]());//SACHIN
[Link]([Link]());//sachin
[Link](s);//
Sachin(no change in original)
Java String trim() method
• The string trim() method eliminates white
spaces before and after string.
• Eg:-
String s=" Sachin ";
[Link](s);// Sachin
[Link]([Link]());//Sachin
• Sachin
• Sachin
Java String startsWith() and endsWith() method

• String s="Sachin";
• [Link]([Link]("Sa"));//true
• [Link]([Link]("n"));//true
• Output:-
• True
• true
Java String charAt() method
• The string charAt() method returns a character
at specified index.
String s="Sachin";
[Link]([Link](0));//S
[Link]([Link](3));//h
Output:-
S
h
Java String length() method
• The string length() method returns length of
the string.
• String s="Sachin";
• [Link]([Link]());//6
• Output:- 6
Java String valueOf() method
• The string valueOf() method coverts given
type such as int, long, float, double, boolean,
char and char array into string.
• int a=10;
• String s=[Link](a);
• [Link](s+10);
• Output:- 1010
Java String replace() method
• The string replace() method replaces all
occurrence of first sequence of character with
second sequence of character.
String s1="Java is a programming language. Java is
a platform. Java is an Island.";
String replaceString=[Link]("Java","Kava");//
replaces all occurrences of "Java" to "Kava"
[Link](replaceString);
• Output:- Kava is a programming language. Kava
is a platform. Kava is an Island.
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.
Example showing difference between String and StringBuffer

class Test
{
public static void main(String args[])
{
String str = "study";
[Link]("tonight");
[Link](str); // Output: study
StringBuffer strB = new StringBuffer("study"); [Link]("tonight");
[Link](strB); // Output: studytonight
}
}
Important Constructors of StringBuffer class

• 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.
Important methods of StringBuffer class
• 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.
• 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.
• public synchronized StringBuffer replace(int startIndex, int
endIndex, String str): is used to replace the string from specified
startIndex and endIndex.
• public synchronized StringBuffer delete(int startIndex, int
endIndex): is used to delete the string from specified startIndex and
endIndex.
• public synchronized StringBuffer reverse(): is used to reverse the
• public int capacity(): is used to return the current capacity.
• public void ensureCapacity(int minimumCapacity): is used to
ensure the capacity at least equal to the given minimum.
• 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 characters.
• public String substring(int beginIndex): is used to return the
substring from the specified beginIndex.
• 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.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
2) StringBuffer 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 ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}
3) StringBuffer 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");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
4) StringBuffer 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");
[Link](1,3);
[Link](sb);//prints Hlo
}
}
5) StringBuffer 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");
[Link]();
[Link](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 A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//
now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
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.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//
now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}
Difference between String and StringBuffer

String StringBuffer
• String class is immutable. • StringBuffer class is
• String is slow and consumes mutable.
more memory when you • StringBuffer is fast and
concat too many strings consumes less memory
because every time it creates when you cancat strings.
new instance. • StringBuffer class doesn't
• String class overrides the override the equals()
equals() method of Object method of Object class.
class. So you can compare
the contents of two strings
by equals() method.
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

• StringBuilder(): creates an empty string


Builder with the initial capacity of 16.
• StringBuilder(String str): creates a string
Builder with the specified string.
• StringBuilder(int length): creates an empty
string Builder with the specified capacity as
length.
Method Description
Important methods of StringBuilder class
public StringBuilder append(String is used to append the specified
s) string with this string. The
append() method is overloaded
like append(char),
append(boolean), append(int),
append(float), append(double) etc.
public StringBuilder insert(int is used to insert the specified
offset, String s) 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.
public StringBuilder replace(int is used to replace the string from
startIndex, int endIndex, String specified startIndex and endIndex.
str)
public StringBuilder delete(int is used to delete the string from
startIndex, int endIndex) specified startIndex and 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
minimumCapacity) least equal to the given minimum.
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
characters.

public String substring(int is used to return the substring


beginIndex) from the specified beginIndex.
public String substring(int is used to return the substring
beginIndex, int endIndex) from the specified beginIndex and
endIndex.
1) StringBuilder append() method
• The StringBuilder append() method concatenates
the given argument with this string.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
2) StringBuilder insert() method
• The StringBuilder insert() method inserts the
given string with this string at the given position.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
[Link](1,"Java");//
now original string is changed
[Link](sb);//prints HJavaello
}
}
3) StringBuilder replace() method
• The StringBuilder replace() method replaces the
given string from the specified beginIndex and
endIndex.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
4) StringBuilder delete() method
• The delete() method of StringBuilder class
deletes the string from the specified beginIndex
to endIndex.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}
5) StringBuilder reverse() method
• The reverse() method of StringBuilder class
reverses the current string.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link]();
[Link](sb);//prints olleH
}
}
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.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//
now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
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.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//
now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}
Difference between StringBuffer and StringBuilder

StringBuffer StringBuilder
• StringBuffer • StringBuilder is non-
is synchronized i.e. thread synchronized i.e. not thread
safe. It means two threads safe. It means two threads
can't call the methods of can call the methods of
StringBuffer simultaneously. StringBuilder
• StringBuffer is less simultaneously.
efficient than StringBuilder. • StringBuilder is more
efficient than StringBuffer.
Java toString() method
• If you want to represent any object as a string, toString()
method comes into existence.
• The toString() method returns the string representation of
the object.
• If you print any object, java compiler internally invokes the
toString() method on the object. So overriding the
toString() method, returns the desired output, it can be the
state of an object etc. depends on your implementation.
• Advantage of Java toString() method
• By overriding the toString() method of the Object class, we
can return values of the object, so we don't need to write
much code.
Understanding problem without toString() method
class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city){


[Link]=rollno;
[Link]=name;
[Link]=city;
}

public static void main(String args[]){


Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

[Link](s1);//compiler writes here [Link]()


[Link](s2);//compiler writes here [Link]()
}
• Output:Student@1fee6fc
• Student@1eed786
• As you can see in the above example, printing
s1 and s2 prints the hashcode values of the
objects but I want to print the values of these
objects. Since java compiler internally calls
toString() method, overriding this method will
return the specified values.
Example of Java toString() method
class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city){


[Link]=rollno;
[Link]=name;
[Link]=city;
}

public String toString(){//overriding the toString() method


return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

[Link](s1);//compiler writes here [Link]()


[Link](s2);//compiler writes here [Link]()
}
}
• Output:
• 101 Raj lucknow
• 102 Vijay ghaziabad
StringTokenizer in Java
• The [Link] class allows you
to break a string into tokens. It is simple way
to break string.
• It doesn't provide the facility to differentiate
numbers, quoted strings, identifiers etc. like
StreamTokenizer class.
Constructors of StringTokenizer class
Constructor Description
StringTokenizer(String str) creates StringTokenizer with
specified string.
StringTokenizer(String str, String creates StringTokenizer with
delim) specified string and delimeter.
StringTokenizer(String str, String creates StringTokenizer with
delim, boolean returnValue) specified string, delimeter and
returnValue. If return value is true,
delimiter characters are
considered to be tokens. If it is
false, delimiter characters serve to
separate tokens.
Methods of StringTokenizer class
Public method Description
boolean hasMoreTokens() checks if there is more tokens
available.
String nextToken() returns the next token from the
StringTokenizer object.
String nextToken(String delim) returns the next token based on
the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return
type is Object.
int countTokens() returns the total number of
tokens.
Simple example of StringTokenizer class
import [Link];
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name
is khan"," ");
while ([Link]()) {
[Link]([Link]());
}
}
}
• Output:
• my
• name
• is
• khan

You might also like