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

Java String

The document discusses various topics related to string handling in Java. It defines what a string is, how strings can be created using string literals and the new keyword, and how strings are immutable objects in Java. It also summarizes string comparison methods like equals(), == operator, and compareTo(), and string concatenation using the + operator and concat() method. Common string class methods for operations like length(), indexOf(), substring() are also briefly mentioned.

Uploaded by

Gopal Sharan
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)
152 views

Java String

The document discusses various topics related to string handling in Java. It defines what a string is, how strings can be created using string literals and the new keyword, and how strings are immutable objects in Java. It also summarizes string comparison methods like equals(), == operator, and compareTo(), and string concatenation using the + operator and concat() method. Common string class methods for operations like length(), indexOf(), substring() are also briefly mentioned.

Uploaded by

Gopal Sharan
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
You are on page 1/ 29

STRING HANDLING

What we will learn in String Handling?

• Concept of String
• Immutable String
• String Comparison
• String Concatenation
• 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',‘a',‘n',‘e',‘l'};  
String s=new String(ch);  
• 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 java.lang.String class
implements Serializable, Comparable and Char
Sequence interfaces.
• 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.
String is Immutable??
• The java String is immutable i.e. it cannot be
changed. Whenever we change any string, a
new instance is created. For mutable string,
we 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 java.lang.String
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)By 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 instanc
e  
2) By new keyword

• String s=new String("Welcome");//creates two
 objects and one reference variable  
//In this 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 
newkeyword  
System.out.println(s1);  
System.out.println(s2);  
System.out.println(s3);  
}}  
Java String class methods

The java.lang.String class provides many useful methods to perform


operations on sequence of char values.

 length()returns int of character count


 trim() returns String exclusive of lead/trail blanks
 toUpperCase(), to LowerCase() returns consistent case
 valueOf() returns String of any primitive
 indexOf() returns int locating a char or substring
 charAt() allows processing of string like char[]
 substring() returns a substring from this string
 replace() changes characters
 replaceAll() changes strings with regular expressions
 split() splits a string into an array of strings using reg.exp.
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.

class immutablestring{  
 public static void main(String args[]){  
  String s=“ABC";  
 s.concat(“DEF ");//concat() method appends the string at the end  
 System.out.println(s);//will print ABC because strings are immutab
le objects  
}  
}  
• But if we explicitly assign it to the reference variable,
it will refer to “ABCDEF" object.For example:
class immutablestring{  
 public static void main(String args[]){  
   String s=“ABC";  
   s=s.concat(" DEF");  
   System.out.println(s);  
 }  
}  
Why string objects are immutable in java?

• Because java uses the concept of string


literal.Suppose there are 5 reference
variables,all referes to one object “ABC".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:
• By equals() method
• By = = operator
• 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 stringcomparison{  
 public static void main(String args[]){  
   String s1=“ABC";  
   String s2=“ABC";  
   String s3=new String("Sachin");  
   String s4=“DEF";  
   System.out.println(s1.equals(s2));//true  
   System.out.println(s1.equals(s3));//true  
   System.out.println(s1.equals(s4));//false  
 }  
}  
Output:true
True
false
2) String compare by == operator
The = = operator compares references not values.

class  stringcomparison{  
 public static void main(String args[]){  
   String s1=“ABC";  
   String s2=“ABC";  
   String s3=new String(“ABC");  
  System.out.println(s1==s2);//true (because both refer to same ins
tance)  
 System.out.println(s1==s3);//false(because s3 refers to instance cr
eated 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
• class stringcomparison{  
•  public static void main(String args[]){  
•    String s1=“ABC";  
•    String s2=“ABC";  
•    String s3=“DEF";  
•    System.out.println(s1.compareTo(s2));//0  
•    System.out.println(s1.compareTo(s3));//1(because s1>s3)  
•    System.out.println(s3.compareTo(s1));//-
1(because s3 < s1 )  
•  }  
• }  

Output:0
1
-1
S2 =s1.toLowerCase;
S2 =s1.toUpperCase;
S2 =s1.replace(‘x’ , ‘y’);
S2 =s1.trim();
S1.equals(s2);
S1.equalsIgnoreCase(s2)
S1.length()
S1.CharAt(n)
S1.CompareTo(s2)
S1.substring(n)
S1.substring(n,m)
S1.indexOf(‘x’)
S1.indexOf(‘x’, n)
String Class
S1.setCharAt(n, ‘x’) modifies the nth character to x
S1.append(s2) Appends the string s2 to s1 at the end
S1.insert(n, s2) Insert the string s2 at the position n of the string s1
S1.setLength(n) sets the length of the string s1 to n. If n<s1.length()
s1 is truncated. If n>s1.length() zeros are added to s1

StringBuffer Class
String Comparision
• There are three ways to compare string in
java:
• By equals() method
• By = = operator
• By compareTo() method
 String compare by equals() method

• 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));//true  
•    System.out.println(s1.equals(s3));//true  
•    System.out.println(s1.equals(s4));//false  
•  }  
• }  
Output:
• true
• True
• false
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");  
   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)  
 }  
}  

Output:
true
false
The String compareTo() method compares String compare by compareTo()and
values lexicographically method
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

class Teststringcomparison4{  
 public static void main(String args[]){  
   String s1="Sachin";  
   String s2="Sachin";  
   String s3="Ratan";  
   System.out.println(s1.compareTo(s2));//0  
   System.out.println(s1.compareTo(s3));//1(because s1>s3)  
   System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
 }  
}  

Output:
0
1
-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";  
•    System.out.println(s);//Sachin Tendulkar  
•  }  
• }  
• Output: Sachin Tendulkar
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)  

• Let's see the example of String concat() method.

class TestStringConcatenation3{  
 public static void main(String args[]){  
   String s1="Sachin ";  
   String s2="Tendulkar";  
   String s3=s1.concat(s2);  
   System.out.println(s3);//Sachin Tendulkar  
  }  
}  
• Output: Sachin Tendulkar
String Length()
• length() method is used to find out length of string. String class has one method length()
called on string object.
• class len
{
public static void main(String arg[])
{
String s=new String("hello world");
String b="this is demo";

System.out.println("Length of s:"+s.length());
System.out.println("Length of b:"+b.length());
}
}
/* Output:
Length of s:11
Length of b:12
*/

You might also like