SlideShare a Scribd company logo
4
Most read
6
Most read
8
Most read
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

More Related Content

PPTX
Constructor in java
Madishetty Prathibha
 
PPTX
Switch statement, break statement, go to statement
Raj Parekh
 
PPTX
Strings in C language
P M Patil
 
PDF
Java conditional statements
Kuppusamy P
 
PPSX
Break and continue
Frijo Francis
 
PPTX
array of object pointer in c++
Arpita Patel
 
PPTX
Structure & union
Rupesh Mishra
 
PPTX
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Constructor in java
Madishetty Prathibha
 
Switch statement, break statement, go to statement
Raj Parekh
 
Strings in C language
P M Patil
 
Java conditional statements
Kuppusamy P
 
Break and continue
Frijo Francis
 
array of object pointer in c++
Arpita Patel
 
Structure & union
Rupesh Mishra
 

What's hot (20)

PPTX
Java tokens
shalinikarunakaran1
 
PPTX
Array in Java
Ali shah
 
PPTX
Union in C programming
Kamal Acharya
 
PPTX
Data types in c++
Venkata.Manish Reddy
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPTX
String Library Functions
Nayan Sharma
 
PPT
Looping statements in Java
Jin Castor
 
PPTX
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
PPTX
Presentation on C Switch Case Statements
Dipesh Panday
 
PPTX
INHERITANCE IN JAVA.pptx
NITHISG1
 
PPTX
Inline function
Tech_MX
 
PPTX
Arrays in java
Arzath Areeff
 
PPTX
Functions in c
sunila tharagaturi
 
DOC
Arrays and Strings
Dr.Subha Krishna
 
PPTX
Constants in java
Manojkumar C
 
PPTX
Operators in java
Then Murugeshwari
 
PPTX
Java program structure
shalinikarunakaran1
 
PPTX
History Of JAVA
ARSLANAHMED107
 
PDF
Strings in java
Kuppusamy P
 
Java tokens
shalinikarunakaran1
 
Array in Java
Ali shah
 
Union in C programming
Kamal Acharya
 
Data types in c++
Venkata.Manish Reddy
 
Methods in Java
Jussi Pohjolainen
 
String Library Functions
Nayan Sharma
 
Looping statements in Java
Jin Castor
 
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Presentation on C Switch Case Statements
Dipesh Panday
 
INHERITANCE IN JAVA.pptx
NITHISG1
 
Inline function
Tech_MX
 
Arrays in java
Arzath Areeff
 
Functions in c
sunila tharagaturi
 
Arrays and Strings
Dr.Subha Krishna
 
Constants in java
Manojkumar C
 
Operators in java
Then Murugeshwari
 
Java program structure
shalinikarunakaran1
 
History Of JAVA
ARSLANAHMED107
 
Strings in java
Kuppusamy P
 
Ad

Similar to Java String Handling (20)

PPS
String and string buffer
kamal kotecha
 
PPTX
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
mohithn2004
 
PPTX
Java string handling
GaneshKumarKanthiah
 
PDF
Module-1 Strings Handling.ppt.pdf
learnEnglish51
 
PPT
07slide
Aboudi Sabbah
 
PPTX
Strings in Java
Abhilash Nair
 
PPTX
L13 string handling(string class)
teach4uin
 
PPT
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
PPSX
String and string manipulation x
Shahjahan Samoon
 
PPT
Strings
naslin prestilda
 
PPTX
String.pptxihugyftgrfxdf bnjklihugyfthfgxvhbjihugyfthcgxcgvjhbkipoihougyfctgf...
minifriendofyou
 
PPTX
Java Strings.pptxJava Strings.pptxJava Strings.pptx
Shivam287777
 
PPT
String and string manipulation
Shahjahan Samoon
 
PPTX
Java String
SATYAM SHRIVASTAV
 
DOCX
Autoboxing and unboxing
Geetha Manohar
 
PPT
Strings power point in detail with examples
rabiyanaseer1
 
PPTX
Programing with java for begniers .pptx
adityaraj7711
 
PPTX
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
PDF
Arrays string handling java packages
Sardar Alam
 
PPTX
Java Strings
RaBiya Chaudhry
 
String and string buffer
kamal kotecha
 
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
mohithn2004
 
Java string handling
GaneshKumarKanthiah
 
Module-1 Strings Handling.ppt.pdf
learnEnglish51
 
07slide
Aboudi Sabbah
 
Strings in Java
Abhilash Nair
 
L13 string handling(string class)
teach4uin
 
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
String and string manipulation x
Shahjahan Samoon
 
String.pptxihugyftgrfxdf bnjklihugyfthfgxvhbjihugyfthcgxcgvjhbkipoihougyfctgf...
minifriendofyou
 
Java Strings.pptxJava Strings.pptxJava Strings.pptx
Shivam287777
 
String and string manipulation
Shahjahan Samoon
 
Java String
SATYAM SHRIVASTAV
 
Autoboxing and unboxing
Geetha Manohar
 
Strings power point in detail with examples
rabiyanaseer1
 
Programing with java for begniers .pptx
adityaraj7711
 
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Arrays string handling java packages
Sardar Alam
 
Java Strings
RaBiya Chaudhry
 
Ad

Recently uploaded (20)

PDF
Introducing Procurement and Supply L2M1.pdf
labyankof
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PDF
Module 3: Health Systems Tutorial Slides S2 2025
Jonathan Hallett
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Sandeep Swamy
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PDF
High Ground Student Revision Booklet Preview
jpinnuck
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTX
How to Manage Global Discount in Odoo 18 POS
Celine George
 
Introducing Procurement and Supply L2M1.pdf
labyankof
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Module 3: Health Systems Tutorial Slides S2 2025
Jonathan Hallett
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Sandeep Swamy
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
Landforms and landscapes data surprise preview
jpinnuck
 
Open Quiz Monsoon Mind Game Final Set.pptx
Sourav Kr Podder
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
High Ground Student Revision Booklet Preview
jpinnuck
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
How to Manage Global Discount in Odoo 18 POS
Celine George
 

Java String Handling

  • 2. 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
  • 3. Char array vs String www.infoviaan.com
  • 4. Char array vs String www.infoviaan.com
  • 5. 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
  • 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 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
  • 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 – 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
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 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 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
  • 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 Thank You www.infoviaan.com 23 www.infoviaan.com