KEMBAR78
Java String Handling | PPTX
String in Java
1
www.infoviaan.com
java.lang.String
• A string is an object that represents a sequence of characters.
• The java.lang.String class is used to create string object.
• It creates two types of objects (in String pool and in heap)
and one reference variable where the variable 's' will refer to
the object in the heap.
• Ex. -
String name = “Infoviaan”;
or
String name = new String(“Infoviaan”);
“Infoviaan”
www.infoviaan.com
Char array vs String
www.infoviaan.com
Char array vs String
www.infoviaan.com
Program -Char array vs String
//Java program to illustate prefering char[] arrays
//over strings for passwords in Java
public class StringVsCharArray
{
public static void main(String[] args)
{
String strPwd = "password";
char[] charPwd = new char[] {'p','a','s','s','w','o','r','d'};
System.out.println("String password: " + strPwd );
System.out.println("Character password: " + charPwd );
//we can use methods of String class.
}
}
www.infoviaan.com
String Methods
• length() : This method returns the length of the String used to
invoke the method.
• charAt(int) : This method requires an integer argument that
indicates the position of the character that the method
returns.This method returns the character located at the String's
specified index. Remember, String indexes are zero-based.
• indexOf(char c) : Return index number of given character.
• indexOf(String s) : Return index number of given String.
• lastIndexOf(String s) : Return last index number of given String.
• replace(char old, char new) : This method returns a String whose
value is that of the String used to invoke the method, updated so
that any occurrence of the char in the first argument is replaced
by the char in the second argument.
• replaceAll(String s, String s1) – replace all string.
www.infoviaan.com
String Methods cont.
• toLowerCase() : This method returns a String whose value is the
String used to invoke the method, but with any uppercase
characters converted to lowercase.
• toUpperCase() : This method returns a String whose value is the
String used to invoke the method, but with any lowercase
characters converted to upper case.
• startsWith(String s) : check start with given string, return Boolean.
• endsWith(String s) : check ends with given string, return Boolean.
• contains(“searchString”): This method returns true of target String
is containing search String provided in the argument.
• trim() : This method returns a String whose value is the String
used to invoke the method, but with any leading or trailing blank
spaces removed.
www.infoviaan.com
String Methods cont.
• subString(int) : The substring() method is used to return a part
(or substring) of the String used to invoke the method. The first
argument represents the starting location (zero-based) of the
substring. If the call has only one argument, the substring returned
will include the characters to the end of the original String.
• equalsIgnoreCase(String s) : This method returns a boolean value
(true or false) depending on whether the value of the String in
the argument is the same as the value of the String used to invoke
the method. This method will return true even when characters in
the String objects being compared have differing cases
• concat(String s) : This method returns a String with the value of
the String passed in to the method appended to the end of the
String used to invoke the method
www.infoviaan.com
Program –String Methods
public class TestStringMethods {
public static void main(String[] args) {
String targetString = "Java is fun to learn";
String s1= "JAVA"; String s2= "Java";
String s3 = " Hello Java ";
System.out.println("Char at index 2(third position): " + targetString.charAt(2));
System.out.println("After Concat: "+ targetString.concat("-Enjoy-"));
System.out.println("Checking equals ignoring case: " +s2.equalsIgnoreCase(s1));
System.out.println("Checking equals with case: " +s2.equals(s1));
System.out.println("Checking Length: "+ targetString.length());
System.out.println("Replace function: "+ targetString.replace("fun", "easy"));
System.out.println("SubString of targetString: "+ targetString.substring(8));
System.out.println("SubString of targetString: "+ targetString.substring(8, 12));
System.out.println("Converting to lower case: "+ targetString.toLowerCase());
System.out.println("Converting to upper case: "+ targetString.toUpperCase());
System.out.println("Triming string: " + s3.trim());
System.out.println("searching s1 in targetString: " + targetString.contains(s1));
System.out.println("searching s2 in targetString: " + targetString.contains(s2));
char [] charArray = s2.toCharArray();
System.out.println("Size of char array: " + charArray.length);
System.out.println("Printing last element of array: " + charArray[3]);
}
}
www.infoviaan.com
String literal & Literal Pool
(Constant Pool)
String s1= “Infoviaan”; String Literal
String s2 = “Infoviaan”;
String s3 = new String(“Infoviaan”);
String s4 = new String(“Infoviaan”);
Infoviaan
Infoviaan Infoviaan
s1 s2
s3
s4
www.infoviaan.com
Program – String literal pool
public class StringPool {
public static void main(String[] args) {
String s1 = "Cat";
String s2 = "Cat";
String s3 = new String("Cat");
System.out.println("s1 == s2
:"+(s1==s2));
System.out.println("s1 == s3
:"+(s1==s3));
}
}
www.infoviaan.com
How many Objects Create?
if
1. String s1 = new String(“Infoviaan”);
//2 object created (1 in heap 1 in pool)
2. String s2 = new String(“Infoviaan”);
//1 object created (in heap)
3. String s3 =“Infoviaan”;
// 0 memory allocation (existed in pool)
4. String s4 = “Infoviaan”;
// 0 memory allocation (existed in pool)
www.infoviaan.com
Program – String equality
public class StringEquality{
public static void main(String args[]){
String s1= “Infoviaan”;
String s2 = “Infoviaan”;
String s3 = new String(“Infoviaan”);
String s4 = new String(“Infoviaan”);
System.out.println(s1==s2); //true
System.out.println(s1==s3); //false
System.out.println(s2==s4); //false
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //true
System.out.println(s2.equals(s4)); //true
System.out.println(s2.equals(s3)); //true
}
}
www.infoviaan.com
String concatenation
• String concatenation forms a new string that is the
combination of multiple strings. There are two ways to
concat string in java:
1. By + (string concatenation) operator
2. By concat() method
www.infoviaan.com
Program - String concatenation
public class TestStringConcatenation{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
String sn=50+30+"Sachin"+40+40;
System.out.println(sn);//80Sachin4040
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
www.infoviaan.com
Program - String Reverse
import java.util.*;
public class ReverseString{
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1 ; i >= 0 ; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of the string: " + reverse);
}
}
www.infoviaan.com
StringBuffer
• StringBuffer in java is used to create modifiable String objects.
• This means that we can use StringBuffer to append, reverse,
replace, concatenate and manipulate Strings or sequence of
characters.
• Corresponding methods under StringBuffer class are respectively
created to adhere to these functions.
www.infoviaan.com
StringBuffer Methods
• length() : Returns the StringBuffer object’s length.
• capacity() : Returns the capacity of the StringBuffer object.
• append() : appends the specified argument string representation at
the end of the existing String Buffer. This method is overloaded for
all the primitive data types and Object.
• insert() : insert() method takes two parameters – the index
integer value to insert a value and the value to be inserted. The
index tells StringBuffer where to insert the passed character
sequence. Again this method is overloaded to work with primitive
data types and Objects.
• reverse() : Reverses the existing String or character sequence
content in the buffer and returns it. The object must have an
existing content or else a NullPointerException is thrown.
• delete(int startIndex, int endIndex) : accepts two integer arguments.
The former serves as the starting delete index and latter as the
ending delete index. Therefore the character sequence between
startIndex and endIndex–1 are deleted. The remaining String content
in the buffer is returned.
www.infoviaan.com
StringBuffer Methods cont.
• deleteCharAt(int index) : deletes single character within the
String inside the buffer. The location of the deleted character
is determined by the passed integer index. The remaining
String content in the buffer is returned.
• replace(int startIndex, int endIndex, String str) : Accepts
three arguments: first two being the starting and ending
index of the existing String Buffer. Therefore the character
sequence between startIndex and endIndex–1 are removed.
Then the String passed as third argument is inserted at
startIndex.
www.infoviaan.com
Program - StringBuffer
public class TestStringBuffer {
public static void main (String[] args) {
StringBuffer s=new StringBuffer("HELLO");
int p=s.length(); int q=s.capacity();
System.out.println("Length of string HELLO="+p);
System.out.println("Capacity of string HELLO="+q);
s.append(“Infoviaan"); System.out.println(s);
s.append(1); System.out.println(s);
s.insert(5, "for"); System.out.println(s);
s.insert(0, 5); System.out.println(s);
s.insert(3, true); System.out.println(s);
s.insert(5, 41.35d); System.out.println(s);
s.insert(8, 41.35f); System.out.println(s);
char data_arr[] = { 'v', 'i', 'y', 'o', 'm' };
s.insert(2, data_arr); System.out.println(s);
s.replace(5,8,"SyS"); System.out.println(s);
s.delete(0,5); System.out.println(s);
s.deleteCharAt(7); System.out.println(s);
s.reverse(); System.out.println(s);
}
}
www.infoviaan.com
String VS StringBuffer
No. String StringBuffer
1) String class is immutable. StringBuffer class is mutable.
2) String is slow and consumes more
memory when you concat too many
strings because every time it
creates new instance.
StringBuffer is fast and
consumes less memory when
you cancat strings.
3) String class overrides the equals()
method of Object class. So you can
compare the contents of two
strings by equals() method.
StringBuffer class doesn't
override the equals()
method of Object class.
www.infoviaan.com
StringBuffer vs StringBuilder
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e.
thread safe. It means two
threads can't call the methods
of StringBuffer simultaneously.
StringBuilder is non-
synchronized i.e. not thread
safe. It means two threads
can call the methods of
StringBuilder simultaneously.
2) StringBuffer is less
efficient than StringBuilder.
StringBuilder is more
efficient than StringBuffer.
www.infoviaan.com
Get in Touch
Thank You
www.infoviaan.com
23
www.infoviaan.com

Java String Handling

  • 1.
  • 2.
    java.lang.String • A stringis an object that represents a sequence of characters. • The java.lang.String class is used to create string object. • It creates two types of objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap. • Ex. - String name = “Infoviaan”; or String name = new String(“Infoviaan”); “Infoviaan” www.infoviaan.com
  • 3.
    Char array vsString www.infoviaan.com
  • 4.
    Char array vsString www.infoviaan.com
  • 5.
    Program -Char arrayvs String //Java program to illustate prefering char[] arrays //over strings for passwords in Java public class StringVsCharArray { public static void main(String[] args) { String strPwd = "password"; char[] charPwd = new char[] {'p','a','s','s','w','o','r','d'}; System.out.println("String password: " + strPwd ); System.out.println("Character password: " + charPwd ); //we can use methods of String class. } } www.infoviaan.com
  • 6.
    String Methods • length(): This method returns the length of the String used to invoke the method. • charAt(int) : This method requires an integer argument that indicates the position of the character that the method returns.This method returns the character located at the String's specified index. Remember, String indexes are zero-based. • indexOf(char c) : Return index number of given character. • indexOf(String s) : Return index number of given String. • lastIndexOf(String s) : Return last index number of given String. • replace(char old, char new) : This method returns a String whose value is that of the String used to invoke the method, updated so that any occurrence of the char in the first argument is replaced by the char in the second argument. • replaceAll(String s, String s1) – replace all string. www.infoviaan.com
  • 7.
    String Methods cont. •toLowerCase() : This method returns a String whose value is the String used to invoke the method, but with any uppercase characters converted to lowercase. • toUpperCase() : This method returns a String whose value is the String used to invoke the method, but with any lowercase characters converted to upper case. • startsWith(String s) : check start with given string, return Boolean. • endsWith(String s) : check ends with given string, return Boolean. • contains(“searchString”): This method returns true of target String is containing search String provided in the argument. • trim() : This method returns a String whose value is the String used to invoke the method, but with any leading or trailing blank spaces removed. www.infoviaan.com
  • 8.
    String Methods cont. •subString(int) : The substring() method is used to return a part (or substring) of the String used to invoke the method. The first argument represents the starting location (zero-based) of the substring. If the call has only one argument, the substring returned will include the characters to the end of the original String. • equalsIgnoreCase(String s) : This method returns a boolean value (true or false) depending on whether the value of the String in the argument is the same as the value of the String used to invoke the method. This method will return true even when characters in the String objects being compared have differing cases • concat(String s) : This method returns a String with the value of the String passed in to the method appended to the end of the String used to invoke the method www.infoviaan.com
  • 9.
    Program –String Methods publicclass TestStringMethods { public static void main(String[] args) { String targetString = "Java is fun to learn"; String s1= "JAVA"; String s2= "Java"; String s3 = " Hello Java "; System.out.println("Char at index 2(third position): " + targetString.charAt(2)); System.out.println("After Concat: "+ targetString.concat("-Enjoy-")); System.out.println("Checking equals ignoring case: " +s2.equalsIgnoreCase(s1)); System.out.println("Checking equals with case: " +s2.equals(s1)); System.out.println("Checking Length: "+ targetString.length()); System.out.println("Replace function: "+ targetString.replace("fun", "easy")); System.out.println("SubString of targetString: "+ targetString.substring(8)); System.out.println("SubString of targetString: "+ targetString.substring(8, 12)); System.out.println("Converting to lower case: "+ targetString.toLowerCase()); System.out.println("Converting to upper case: "+ targetString.toUpperCase()); System.out.println("Triming string: " + s3.trim()); System.out.println("searching s1 in targetString: " + targetString.contains(s1)); System.out.println("searching s2 in targetString: " + targetString.contains(s2)); char [] charArray = s2.toCharArray(); System.out.println("Size of char array: " + charArray.length); System.out.println("Printing last element of array: " + charArray[3]); } } www.infoviaan.com
  • 10.
    String literal &Literal Pool (Constant Pool) String s1= “Infoviaan”; String Literal String s2 = “Infoviaan”; String s3 = new String(“Infoviaan”); String s4 = new String(“Infoviaan”); Infoviaan Infoviaan Infoviaan s1 s2 s3 s4 www.infoviaan.com
  • 11.
    Program – Stringliteral pool public class StringPool { public static void main(String[] args) { String s1 = "Cat"; String s2 = "Cat"; String s3 = new String("Cat"); System.out.println("s1 == s2 :"+(s1==s2)); System.out.println("s1 == s3 :"+(s1==s3)); } } www.infoviaan.com
  • 12.
    How many ObjectsCreate? if 1. String s1 = new String(“Infoviaan”); //2 object created (1 in heap 1 in pool) 2. String s2 = new String(“Infoviaan”); //1 object created (in heap) 3. String s3 =“Infoviaan”; // 0 memory allocation (existed in pool) 4. String s4 = “Infoviaan”; // 0 memory allocation (existed in pool) www.infoviaan.com
  • 13.
    Program – Stringequality public class StringEquality{ public static void main(String args[]){ String s1= “Infoviaan”; String s2 = “Infoviaan”; String s3 = new String(“Infoviaan”); String s4 = new String(“Infoviaan”); System.out.println(s1==s2); //true System.out.println(s1==s3); //false System.out.println(s2==s4); //false System.out.println(s1.equals(s2)); //true System.out.println(s1.equals(s3)); //true System.out.println(s2.equals(s4)); //true System.out.println(s2.equals(s3)); //true } } www.infoviaan.com
  • 14.
    String concatenation • Stringconcatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java: 1. By + (string concatenation) operator 2. By concat() method www.infoviaan.com
  • 15.
    Program - Stringconcatenation public class TestStringConcatenation{ public static void main(String args[]){ String s="Sachin"+" Tendulkar"; System.out.println(s);//Sachin Tendulkar String sn=50+30+"Sachin"+40+40; System.out.println(sn);//80Sachin4040 String s1="Sachin "; String s2="Tendulkar"; String s3=s1.concat(s2); System.out.println(s3);//Sachin Tendulkar } } www.infoviaan.com
  • 16.
    Program - StringReverse import java.util.*; public class ReverseString{ public static void main(String args[]) { String original, reverse = ""; Scanner in = new Scanner(System.in); System.out.println("Enter a string to reverse"); original = in.nextLine(); int length = original.length(); for (int i = length - 1 ; i >= 0 ; i--) reverse = reverse + original.charAt(i); System.out.println("Reverse of the string: " + reverse); } } www.infoviaan.com
  • 17.
    StringBuffer • StringBuffer injava is used to create modifiable String objects. • This means that we can use StringBuffer to append, reverse, replace, concatenate and manipulate Strings or sequence of characters. • Corresponding methods under StringBuffer class are respectively created to adhere to these functions. www.infoviaan.com
  • 18.
    StringBuffer Methods • length(): Returns the StringBuffer object’s length. • capacity() : Returns the capacity of the StringBuffer object. • append() : appends the specified argument string representation at the end of the existing String Buffer. This method is overloaded for all the primitive data types and Object. • insert() : insert() method takes two parameters – the index integer value to insert a value and the value to be inserted. The index tells StringBuffer where to insert the passed character sequence. Again this method is overloaded to work with primitive data types and Objects. • reverse() : Reverses the existing String or character sequence content in the buffer and returns it. The object must have an existing content or else a NullPointerException is thrown. • delete(int startIndex, int endIndex) : accepts two integer arguments. The former serves as the starting delete index and latter as the ending delete index. Therefore the character sequence between startIndex and endIndex–1 are deleted. The remaining String content in the buffer is returned. www.infoviaan.com
  • 19.
    StringBuffer Methods cont. •deleteCharAt(int index) : deletes single character within the String inside the buffer. The location of the deleted character is determined by the passed integer index. The remaining String content in the buffer is returned. • replace(int startIndex, int endIndex, String str) : Accepts three arguments: first two being the starting and ending index of the existing String Buffer. Therefore the character sequence between startIndex and endIndex–1 are removed. Then the String passed as third argument is inserted at startIndex. www.infoviaan.com
  • 20.
    Program - StringBuffer publicclass TestStringBuffer { public static void main (String[] args) { StringBuffer s=new StringBuffer("HELLO"); int p=s.length(); int q=s.capacity(); System.out.println("Length of string HELLO="+p); System.out.println("Capacity of string HELLO="+q); s.append(“Infoviaan"); System.out.println(s); s.append(1); System.out.println(s); s.insert(5, "for"); System.out.println(s); s.insert(0, 5); System.out.println(s); s.insert(3, true); System.out.println(s); s.insert(5, 41.35d); System.out.println(s); s.insert(8, 41.35f); System.out.println(s); char data_arr[] = { 'v', 'i', 'y', 'o', 'm' }; s.insert(2, data_arr); System.out.println(s); s.replace(5,8,"SyS"); System.out.println(s); s.delete(0,5); System.out.println(s); s.deleteCharAt(7); System.out.println(s); s.reverse(); System.out.println(s); } } www.infoviaan.com
  • 21.
    String VS StringBuffer No.String StringBuffer 1) String class is immutable. StringBuffer class is mutable. 2) String is slow and consumes more memory when you concat too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when you cancat strings. 3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class. www.infoviaan.com
  • 22.
    StringBuffer vs StringBuilder No.StringBuffer StringBuilder 1) StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non- synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. 2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer. www.infoviaan.com
  • 23.
    Get in Touch ThankYou www.infoviaan.com 23 www.infoviaan.com