String Handling in Java
String Handling in Java
The basic aim of 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
Java String contains an immutable sequence of Unicode characters. Java String is differ from
string in C or C++, where (in C or C++) string is simply an array of char. String class is
encapsulated under java.lang package.
Immutable class means that once an object is created, we cannot change its content. In Java, . In
Java String, Integer, Byte, Short, Float, Double and all other wrapper classes are immutable.
// An immutable class
public final class Student
{
final String name;
final int roll_no;
// Driver class
class Result
{
public static void main(String args[])
{
Student s = new Student("Hitesh", 18);
System.out.println(s.name);
System.out.println(s.roll_no);
}
}
Character
String:
String is a sequence of characters enclosed within double quotes (" ") is known as String.
Similarly to store the string data and to perform various operation on String data, we have three
String
StringBuffer
StringBuilder
It is a predefined class in java.lang package can be used to handle the String. String class
is immutable that means whose content can not be changed at the time of execution of program.
String class object is immutable that means when we create an object of String class it never
Example:
Example
class StringHandling
{
public static void main(String arg[])
{
String s=new String("java");
s.concat("software");
System.out.println(s);
}
}
Output
java
Explanation: Here we can not change the object of String class so output is only java not java
software.
Methods of String class
length()
class StringHandling
{
public static void main(String arg[])
{
int l;
String s=new String("Java");
l=s.length();
System.out.println("Length: "+l);
}
}
Output
Length: 4
charAt(index)
class StringHandling
{
public static void main(String arg[])
{
char c;
String s=new String("Java");
c=s.charAt(2);
System.out.println("Character: "+c);
}
}
Output
Character: v
toUpperCase()
toUpperCase(): This method is use to convert lower case string into upper case.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java";
System.out.println("String: "+s.toUpperCase());
}
}
Output
String: JAVA
toLowerCase()
toLowerCase(): This method is used to convert lower case string into upper case.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="JAVA";
System.out.println("String: "+s.toLowerCase());
}
}
Output
String: java
concat()
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
System.out.println("Combined String: "+s1.concat(s2));
}
}
Output
equals()
equals(): This method is used to compare two strings, It return true if strings are same otherwise
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
String s3="Hitesh";
System.out.println("Compare String: "+s1.equals(s2));
System.out.println("Compare String: "+s1.equals(s3));
}
}
Output
equalsIgnoreCase()
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="HITESH";
String s3="Raddy";
System.out.println("Compare String: "+s1.equalsIgnoreCase(s2));
System.out.println("Compare String: "+s1.equalsIgnoreCase(s3));
}
}
Output
compareTo()
compareTo(): This method is used to compare two strings by taking unicode values, It return 0 if
the string are same otherwise return +ve or -ve integer values.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Hitesh";
String s2="Raddy";
int i;
i=s1.compareTo(s2);
if(i==0)
{
System.out.println("Strings are same");
}
else
{
System.out.println("Strings are not same");
}
}
}
Output
compareToIgnoreCase()
Output
startsWith()
startsWith(): This method return true if string is start with given another string, otherwise it
returns false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.startsWith("Java"));
}
}
Output
true
endsWith()
endsWith(): This method return true if string is end with given another string, otherwise it returns
false.
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.endsWith("language"));
}
}
Output
true
subString()
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8)); // 8 is starting index
}
}
Output
programming language
Example
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8, 12));
}
}
Output
prog
indexOf()
indexOf(): This method is used find the index value of given string. It always gives starting index
class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.indexOf("programming"));
}
}
Output
lastIndexOf()
lastIndexOf(): This method used to return the starting index value of last occurence of the given
string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s1="Java is programming language";
String s2="Java is good programming language";
System.out.println(s1.lastIndexOf("programming"));
System.out.println(s2.lastIndexOf("programming"));
}
}
Output
13
trim()
trim(): This method remove space which are available before starting of string and after ending
of string.
Example
class StringHandling
{
public static void main(String arg[])
{
String s=" Java is programming language ";
System.out.println(s.trim());
}
}
Output
split()
split(): This method is used to divide the given string into number of parts based on delimiter
class StringHandling
{
public static void main(String arg[])
{
String s="contact@tutorial4us.com";
String[] s1=s.split("@"); // divide string based on @
for(String c:s1) // foreach loop
{
System.out.println(c);
}
}
}
Output
contact
@tutorial4us.com
replace()
replace(): This method is used to return a duplicate string by replacing old character with new
character.
class StringHandling
{
public static void main(String arg[])
{
String s1="java";
String s2=s1.replace('j', 'k');
System.out.println(s2);
}
}
Output
kava
StringBuffer Class in Java
It is a predefined class in java.lang package can be used to handle the String, whose object is
StringBuffer class is working with thread safe mechanism that means multiple thread are not
it can be change.
Example StringBuffer
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java");
sb.append("software");
System.out.println(sb);
}
}
Output
javasoftware
javasoftware.
String StringBuffer
When we create an object of String class When we create an object of StringBuffer class by
by default no additional character memory default we get 16 additional character memory
space is created. space.
Both of them are belongs to public final. so that they never participates in
inheritance that is is-A relationship is not possible but they can always participates in
As-A and Uses-A relationship.
reverse()
reverse(): This method is used to reverse the given string and also the new value is replaced by
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java code");
System.out.println(sb.reverse());
}
}
Output
edoc avaj
insert()
insert(): This method is used to insert either string or character or integer or real constant or
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("this is my java code");
System.out.println(sb.insert(11, "first "));
}
}
Output
append(): This method is used to add the new string at the end of original string.
Example
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java is easy");
System.out.println(sb.append(" to learn"));
}
}
Output
replace()
replace() This method is used to replace any old string with new string based on index value.
Example
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("This is my code");
System.out.println(sb.replace(8, 10, "java"));
}
}
Output
deleteCharAt()
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java");
System.out.println(sb.deleteCharAt(3));
}
}
Output
jav
delete()
delete(): This method is used to delete string form given string based on index value.
Example
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java is easy to learn");
StringBuffer s;
s=sb.delete(8, 13);
System.out.println(sb);
}
}
Output
java is to learn
Explanation: In above example string will be deleted which is existing between 8 and 13 index
value.
toString()
toString(): This method is used to convert mutable string value into immutable string.
Example
class StringHandling
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("java");
String s=sb.toString();
System.out.println(s);
s.concat("code");
}
}
Output
java
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.
1. class StringBuilderExample{
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. }
1. class StringBuilderExample2{
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. }
1. class StringBuilderExample3{
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. }
1. class StringBuilderExample4{
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. }
1. class StringBuilderExample5{
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. }
1. class StringBuilderExample6{
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. }
1. class StringBuilderExample7{
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. }