Established as per the Section 2(f) of the UGC Act, 1956
Approved by AICTE, COA and BCI, New Delhi
Lecture 3.1
STRINGS
S ch o o l o f Co mp u t e r S c i e n ce a n d E n g i n e e r i n g
TOPIC OF THE LECTURE
Strings
Creating a String object
String class methods
 concat()
 equals()
 Substirng ()
 compareTo()
String class methods
 toLowerCase()
 toUpperCase()
 charAt()
 length()
 replace()
 trim()
 split()
 contains()
 isEmpty()
String Constant Pool
Strings
De fi nition
STRINGS
Definition
 String is a sequence of characters
 String is an object that represents a sequence of characters.
 java.lang.String class is used to create a string object.
 String is a sequence of characters. In java, objects of String are immutable
which means a constant and cannot be changed once created.
 Whenever a change to a String is made, an entirely new String is created.
STRINGS
Creating string object
There are two ways to create String object:
Two ways
By string literal
By new keyword
STRINGS
Creating string object
1) String Literal
Java String literal is created by using double quotes.
Example:
String s=“REVA";
It doesn't create a new instance
String s1=“REVA";
String s2=“REVA";
“REVA”
STRINGS
Creating string object
2) By new keyword
String s1=new String(“REVA");
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal “REVA" will be placed in the string constant pool. The
variable s1 will refer to the object in a heap (non-pool).
STRINGS
class StringE
{
public static void main(String args[])
{
String s1="REVA"; //creating string by Java string literal
char ch[]={'u','n','i','v','e','r','s','i','t','y'};
String s2=new String(ch); //converting char array to string
String s3=new String("BANGALORE");
//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Example program
Output:
C:lks2020unit 1>javac StringE.java
C:lks2020unit 1>java StringE
REVA
university
BANGALORE
STRING CONSTANT POOL
• A Java String Pool is a place in heap memory where all the strings
defined in the program are stored.
• A separate place in a stack is there where the variable storing the
string is stored.
• Whenever we create a new string object, JVM checks for the presence
of the object in the String pool, If String is available in the pool, the
same object reference is shared with the variable, else a new object
is created.
• When we declare a string, an object of type String is created in the
stack, while an instance with the value of the string is created in the
heap.
import java.util.*;
class Demo{
public static void main(String[] args)
{
String s1 = "abc“, s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
if (s1 == s2)
System.out.println("Yes");
else
System.out.println("No");
if (s3 == s4)
System.out.println("Yes");
else
System.out.println("No");
}
}
Output:
Yes
No
String str1 = "Hello";
String str2 = "Hello";
String str3 = "Class";
String str1 = new String("John");
String str2 = new String("Doe");
Strings
Str ing me thods
STRINGS
• In java, 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
java string concat()
STRINGS
java string concat()
For Example:
class TestStringConcatenation1
{
public static void main(String args[])
{
String s="Sachin"+" Tendulkar";
System.out.println(s);//
Sachin Tendulkar
}
}
1) String Concatenation by + (string concatenation) operator
Java string concatenation operator (+) is used to add strings.
Output:
Sachin
Tendulkar
STRINGS
java string concat()
For Example:
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
}
}
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)
Output:
Sachin
Tendulkar
STRINGS
concat() example program
public class ConcatExample2
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "Reva";
String str3 = "University";
// Concatenating one string
String str4 = str1.concat(str2);
System.out.println(str4);
// Concatenating multiple strings
String str5 = str1.concat(str2).concat(str3);
System.out.println(str5);
}
}
Output:
HelloReva
HelloRevaUniversity
STRINGS
substring() example program
public class TestSubstring
{
public static void main(String args[])
{
String s="Sachin Tendulkar";
System.out.println(s.substring(6));//Tendulkar.
System.out.println(s.substring(0,6));//Sachin.
}
}
C:pgrs>java TestSubstring
Tendulkar
Sachin
The java string substring() method returns a part of the string.
STRINGS
String comparison
Can be done in 3 ways
 equals()
The java string equals() method compares the two given strings based on the content
of the string. If any character is not matched, it returns false. If all characters are matched, it
returns true.
 compareTo()
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.
s1 == s2 : The method returns 0. s1 > s2 : The method returns a positive value.s1 < s2 : The
method returns a negative value.
 ==
Compare reference not the values. If the reference is not matched, it returns false. If all
the reference is , it returns true.
STRINGS
String equals()
import java.lang.String;
public class EqualsExample{
public static void main(String args[]){
String s1=“reva";
String s2=“reva";
String s3=“REVA";
String s4="python";
System.out.println(s1.equals(s2));//
true because content and case is same
System.out.println(s1.equals(s3));//
false because case is not same
System.out.println(s1.equals(s4));//
false because content is not same
}}
Output:
true
false
false
STRINGS
String compareTo()
class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}
C:pgrs>java
CompareExam
ple
0
-5
-1
2
t s r q p o n m l k
j i h g f e d c b a
STRINGS
String ==
class Teststringcomparison4
{
public static void main(String args[]){
String s1=“Reva";
String s2=“Reva";
String s3=“University";
String s4=new String(“Reva”);
System.out.println(s1==s2);
System.out.println(s1==s3)
System.out.println(s1==s4)
}
}
Output:
true
false
false
Strings
Str ing me thods
import java.io.*;
public class Test
{
public static void main(String args[])
{
String Str = new String("Welcome to REVA");
System.out.print("Return Value :");
System.out.println(Str.toLowerCase());
}
}
Output
Return Value :welcome to reva
STRINGS
String toLowerCase() Method
Syntax:
public String toLowerCase()
import java.io.*;
public class Test
{
public static void main(String args[])
{
String Str = new String("Welcome to reva");
System.out.print("Return Value :" );
System.out.println(Str.toUpperCase() );
}
}
Output
Return Value :WELCOME TO REVA
STRINGS
String toUpperCase() Method
Syntax:
public String toUpperCase()
public class CharAtExample
{
public static void main(String args[])
{
String name=“REVA UNIVERSITY”;
char ch=name.charAt(5);
System.out.println(ch);
}
}
Output:
U
STRINGS
Java String charAt()
Syntax:
public char charAt(int index)
public class LengthE
{
public static void main(String args[])
{
String s1=“corona virus";
String s2=“India";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}
Output:
string length is: 12
string length is: 5
STRINGS
Java String length()
Syntax:
public int length()
public class replaceE
{
public static void main(String args[])
{
String s1=“St_y Home Stay S_fe";
String replaceString=s1.replace(‘_',‘a');
System.out.println(replaceString);
}
}
Output:
Stay Home Stay Safe
STRINGS
Java String replace()
Syntax:
public String replace(char oldChar, char newChar)
public class trimE
{
public static void main(String args[])
{
String s1=" REVA ";
System.out.println(s1+"Bangalore");
System.out.println(s1.trim()+"Bangalore");
}
}
Output:
C:pgrs>java trimE
REVA Bangalore
REVABangalore
STRINGS
Java String trim() that eliminates leading and trailing spaces
Syntax:
public String trim()
public class SplitE
{
public static void main(String args[])
{
String s1="REVA University best educational institute";
String[] words=s1.split(“ ");
for(String w:words)
{
System.out.println(w);
}
}
}
Output:
REVA
University
best
educational
Institute
STRINGS
Java String split()
Syntax:
public String split(String regex)
•
class Main
{
public static void main(String[] args)
{
String s1="REVA_University_best_educational_institute";
String[] words=s1.split("_",1); for(String w:words)
{
System.out.println(w);
}
}
}
Output:
REVA_University_best_educational_institute
STRINGS
Java String split()
Syntax:
public String split(String regex)
•
class Main
{
public static void main(String[] args)
{
String s1="REVA_University_best_educational_institute";
String[] words=s1.split("_",3); for(String w:words)
{
System.out.println(w);
}
}
}
Output:
REVA
University
best_educational_institute
STRINGS
Java String split()
Syntax:
public String split(String regex)
•
class containsE
{
public static void main(String args[])
{
String name="what do you know about me";
System.out.println(name.contains("do you"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}
}
Output:
true
true
false
STRINGS
Java String contains()
Syntax:
public boolean contains(CharSequence sequence)
•
public class IsEmptyE
{
public static void main(String args[])
{
String s1="";
String s2=“COVID-19";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}
Output:
true
false
STRINGS
Java String isEmpty()
Syntax:
public boolean isEmpty()
•
public class IsEmptyExample
{
public static void main(String args[]){
String s1="";
String s2="javatpoint";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}}
Output:
true
false
STRINGS
Java String isEmpty()
Syntax:
public boolean isEmpty()
•
CHARSEQUENCE INTERFACE
CharSequence Interface is used for representing the sequence of
Characters in Java.
1. String
2. StringBuffer
3. StringBuilder
1. STRING
String is an immutable class which means a constant and cannot be
changed once created and if wish to change , we need to create an new
object and even the functionality it provides like toupper, tolower, etc all
these return a new object , its not modify the original object. It is
automatically thread safe.
String str= "geeks";
or
String str= new String("geeks")
2. STRINGBUFFER
• String represents fixed-length, immutable character sequences
• StringBuffer represents growable and writable character sequences
means it is immutable in nature
• It is thread safe class , we can use it when we have multi threaded
environment and shared object of string buffer i.e, used by mutiple
thread.
• Allow you to modify the contents of a string without creating a new
object every time.
• Syntax:
StringBuffer demoString = new StringBuffer(“REVA");
METHODS OF STRINGBUFFER
1. The initial capacity of a StringBuffer can be specified when it is
created, or it can be set later with the ensureCapacity() method.
2. The append() method is used to add characters, strings, or other
objects to the end of the buffer.
3. The insert() method is used to insert characters, strings, or other
objects at a specified position in the buffer.
4. The delete() method is used to remove characters from the buffer.
5. The reverse() method is used to reverse the order of the characters in
the buffer.
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer ("Hello");
sb.append("Java"); // now original string is changed
System.out.println(sb);
sb.insert(1, "Java"); // Now original string is changed
System.out.println(sb);
sb.replace(1, 3, “REVA");// replaces the given string
from the specified beginIndex and endIndex-1
System.out.println(sb);
sb.delete(1, 3);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
StringBuffer sb1 = new StringBuffer();
System.out.println(“Default capacity
is:"+sb1.capacity());//default 16
sb1.append("java is my favourite
language");
System.out.println(sb1.capacity());// now
it becomes (16*2)+2=34
}
}
Output:
HelloJava
HJavaelloJava
HREVAvaelloJava
HVAvaelloJava
avaJolleavAVH
Default capacity is:16
34
STRINGBUILDER
• StringBuilder in Java represents a mutable sequence of characters
• As it creates a mutable sequence of characters and it is not thread
safe and its used only within the thread.
• It is mainly used for single threaded program.
• The StringBuilder class differs from the StringBuffer class on the basis
of synchronization.
• The StringBuilder class provides no guarantee of synchronization
whereas the StringBuffer class does. Therefore this class is designed
for use as a drop-in replacement for StringBuffer in places where the
StringBuffer was being used by a single thread
• Syntax:
StringBuilder demoString = new StringBuilder();
demoString.append(“REVA");
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("world!");
System.out.println(sb.toString()); // Output: "Hello world!"
sb.insert(6, "beautiful ");
System.out.println(sb.toString()); // Output: "Hello beautiful world!"
sb.reverse();
System.out.println(sb.toString()); // Output: "!dlrow lufituaeb olleH"
}
Output:
Hello world!
Hello beautiful world!
!dlrow lufituaeb olleH
CREATING IMMUTABLE CLASS
There are many immutable classes like String, Boolean, Byte, Short, Integer,
Long, Float, Double etc.
In short, all the wrapper classes and String class is immutable.
We can also create immutable class by creating final class that have final
data members as the example given below:
public final class Employee {
final String pancardNumber;
public Employee(String pancardNumber) {
this.pancardNumber=pancardNumber;
}
public String getPancardNumber() {
return pancardNumber;
}
}
public class ImmutableDemo {
public static void main(String ar[]) {
Employee e = new Employee("ABC123");
String s1 = e.getPancardNumber();
System.out.println("Pancard Number: " + s1);
} }
Output:
Pancard Number: ABC123
TO STRING ()
• 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. depending on your implementation.
WITHOUT USING TOSTRING() METHOD
class Student{
int rollno;
String name, city;
Student(int rollno, String name, String city){
this.rollno=rollno; this.name=name; this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,“ABC",“Bangalore");
Student s2=new Student(102,“XYZ",“Mysore");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:
Student@1fee6fc
Student@1eed786
WITH USING TOSTRING() METHOD
class Student {
int rollno;
String name, city;
Student(int rollno, String name, String city) {
this.rollno=rollno; this.name=name; this.city=city;
}
public String toString() {//overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]) {
Student s1=new Student(101,“ABC",“Bangalore");
Student s2=new Student(102,“XYZ",“Mysore");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
} }
101 ABC Bangalore
102 XYZ Mysore
STRIGTOKENIZER CLASS
• StringTokenizer class in Java is used to break a string into tokens.
• The java.util.StringTokenizer class allows you to break a String into
tokens.
• In the StringTokenizer class, the delimiters can be provided at the time
of creation or one by one to the tokens.
Constructor Description
StringTokenizer(String str) It creates StringTokenizer with specified string.
StringTokenizer(String str, String
delim)
It creates StringTokenizer with specified string and
delimiter.
StringTokenizer(String str, String
delim, boolean returnValue)
It creates StringTokenizer with specified string, delimiter
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 STRIGTOKENIZER CLASS
Methods Description
boolean hasMoreTokens() It checks if there is more tokens available.
String nextToken() It returns the next token from the
StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.
Object nextElement() It is the same as nextToken() but its return type
is Object.
int countTokens() It returns the total number of tokens.
import java.util.StringTokenizer;
public class StringTokenizer1
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Demonstrating methods from Stri
ngTokenizer class"," ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
Demonstrating
methods
from
StringTokenizer
class
THANK YOU

More Related Content

PPTX
Programing with java for begniers .pptx
PPTX
Java Strings.pptxJava Strings.pptxJava Strings.pptx
PPTX
Java String Handling
PPTX
String in java, string constructors and operations
PPT
Charcater and Strings.ppt Charcater and Strings.ppt
PPS
String and string buffer
DOCX
Autoboxing and unboxing
PPTX
Module-5-hjhjhjkhdjkhjhjhhhjhjhhhhj.pptx
Programing with java for begniers .pptx
Java Strings.pptxJava Strings.pptxJava Strings.pptx
Java String Handling
String in java, string constructors and operations
Charcater and Strings.ppt Charcater and Strings.ppt
String and string buffer
Autoboxing and unboxing
Module-5-hjhjhjkhdjkhjhjhhhjhjhhhhj.pptx

Similar to 3.1 STRINGS (1) java jksdbkjdbsjsef.pptx (20)

PPTX
10619416141061941614.106194161fff4..pptx
PPTX
Java string , string buffer and wrapper class
PPT
07slide
PPTX
CH1 ARRAY (1).pptx
PPTX
L13 string handling(string class)
PPT
JAVA CONCEPTS
PPTX
Day_5.1.pptx
PPT
Chapter 7 String
PPTX
Strings in Java
PPTX
Java String
PDF
Java R20 - UNIT-5.pdf
PDF
Strings in java
PDF
Module-1 Strings Handling.ppt.pdf
PPTX
Java string handling
PPT
String Handling
PPT
String classes and its methods.20
PPTX
Computer programming 2 Lesson 12
DOCX
Java R20 - UNIT-5.docx
PPTX
String.pptxihugyftgrfxdf bnjklihugyfthfgxvhbjihugyfthcgxcgvjhbkipoihougyfctgf...
PPT
String and string manipulation
10619416141061941614.106194161fff4..pptx
Java string , string buffer and wrapper class
07slide
CH1 ARRAY (1).pptx
L13 string handling(string class)
JAVA CONCEPTS
Day_5.1.pptx
Chapter 7 String
Strings in Java
Java String
Java R20 - UNIT-5.pdf
Strings in java
Module-1 Strings Handling.ppt.pdf
Java string handling
String Handling
String classes and its methods.20
Computer programming 2 Lesson 12
Java R20 - UNIT-5.docx
String.pptxihugyftgrfxdf bnjklihugyfthfgxvhbjihugyfthcgxcgvjhbkipoihougyfctgf...
String and string manipulation
Ad

Recently uploaded (20)

PDF
Applications of Equal_Area_Criterion.pdf
PPT
Chapter 1 - Introduction to Manufacturing Technology_2.ppt
PDF
Unit1 - AIML Chapter 1 concept and ethics
PDF
Accra-Kumasi Expressway - Prefeasibility Report Volume 1 of 7.11.2018.pdf
PPTX
A Brief Introduction to IoT- Smart Objects: The "Things" in IoT
PDF
Computer System Architecture 3rd Edition-M Morris Mano.pdf
PPTX
Chapter 2 -Technology and Enginerring Materials + Composites.pptx
PDF
Java Basics-Introduction and program control
PDF
Design Guidelines and solutions for Plastics parts
PPTX
Principal presentation for NAAC (1).pptx
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
MLpara ingenieira CIVIL, meca Y AMBIENTAL
PPTX
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
PDF
20250617 - IR - Global Guide for HR - 51 pages.pdf
PPTX
CN_Unite_1 AI&DS ENGGERING SPPU PUNE UNIVERSITY
PPTX
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PPTX
Measurement Uncertainty and Measurement System analysis
PPTX
Module 8- Technological and Communication Skills.pptx
PPTX
Information Storage and Retrieval Techniques Unit III
Applications of Equal_Area_Criterion.pdf
Chapter 1 - Introduction to Manufacturing Technology_2.ppt
Unit1 - AIML Chapter 1 concept and ethics
Accra-Kumasi Expressway - Prefeasibility Report Volume 1 of 7.11.2018.pdf
A Brief Introduction to IoT- Smart Objects: The "Things" in IoT
Computer System Architecture 3rd Edition-M Morris Mano.pdf
Chapter 2 -Technology and Enginerring Materials + Composites.pptx
Java Basics-Introduction and program control
Design Guidelines and solutions for Plastics parts
Principal presentation for NAAC (1).pptx
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
MLpara ingenieira CIVIL, meca Y AMBIENTAL
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
20250617 - IR - Global Guide for HR - 51 pages.pdf
CN_Unite_1 AI&DS ENGGERING SPPU PUNE UNIVERSITY
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
Exploratory_Data_Analysis_Fundamentals.pdf
Measurement Uncertainty and Measurement System analysis
Module 8- Technological and Communication Skills.pptx
Information Storage and Retrieval Techniques Unit III
Ad

3.1 STRINGS (1) java jksdbkjdbsjsef.pptx

  • 1. Established as per the Section 2(f) of the UGC Act, 1956 Approved by AICTE, COA and BCI, New Delhi Lecture 3.1 STRINGS S ch o o l o f Co mp u t e r S c i e n ce a n d E n g i n e e r i n g
  • 2. TOPIC OF THE LECTURE Strings Creating a String object String class methods  concat()  equals()  Substirng ()  compareTo() String class methods  toLowerCase()  toUpperCase()  charAt()  length()  replace()  trim()  split()  contains()  isEmpty() String Constant Pool
  • 4. STRINGS Definition  String is a sequence of characters  String is an object that represents a sequence of characters.  java.lang.String class is used to create a string object.  String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.  Whenever a change to a String is made, an entirely new String is created.
  • 5. STRINGS Creating string object There are two ways to create String object: Two ways By string literal By new keyword
  • 6. STRINGS Creating string object 1) String Literal Java String literal is created by using double quotes. Example: String s=“REVA"; It doesn't create a new instance String s1=“REVA"; String s2=“REVA"; “REVA”
  • 7. STRINGS Creating string object 2) By new keyword String s1=new String(“REVA"); In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal “REVA" will be placed in the string constant pool. The variable s1 will refer to the object in a heap (non-pool).
  • 8. STRINGS class StringE { public static void main(String args[]) { String s1="REVA"; //creating string by Java string literal char ch[]={'u','n','i','v','e','r','s','i','t','y'}; String s2=new String(ch); //converting char array to string String s3=new String("BANGALORE"); //creating Java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); } } Example program Output: C:lks2020unit 1>javac StringE.java C:lks2020unit 1>java StringE REVA university BANGALORE
  • 9. STRING CONSTANT POOL • A Java String Pool is a place in heap memory where all the strings defined in the program are stored. • A separate place in a stack is there where the variable storing the string is stored. • Whenever we create a new string object, JVM checks for the presence of the object in the String pool, If String is available in the pool, the same object reference is shared with the variable, else a new object is created. • When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap.
  • 10. import java.util.*; class Demo{ public static void main(String[] args) { String s1 = "abc“, s2 = "abc"; String s3 = new String("abc"); String s4 = new String("abc"); if (s1 == s2) System.out.println("Yes"); else System.out.println("No"); if (s3 == s4) System.out.println("Yes"); else System.out.println("No"); } } Output: Yes No
  • 11. String str1 = "Hello"; String str2 = "Hello"; String str3 = "Class"; String str1 = new String("John"); String str2 = new String("Doe");
  • 13. STRINGS • In java, 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 java string concat()
  • 14. STRINGS java string concat() For Example: class TestStringConcatenation1 { public static void main(String args[]) { String s="Sachin"+" Tendulkar"; System.out.println(s);// Sachin Tendulkar } } 1) String Concatenation by + (string concatenation) operator Java string concatenation operator (+) is used to add strings. Output: Sachin Tendulkar
  • 15. STRINGS java string concat() For Example: 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 } } 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) Output: Sachin Tendulkar
  • 16. STRINGS concat() example program public class ConcatExample2 { public static void main(String[] args) { String str1 = "Hello"; String str2 = "Reva"; String str3 = "University"; // Concatenating one string String str4 = str1.concat(str2); System.out.println(str4); // Concatenating multiple strings String str5 = str1.concat(str2).concat(str3); System.out.println(str5); } } Output: HelloReva HelloRevaUniversity
  • 17. STRINGS substring() example program public class TestSubstring { public static void main(String args[]) { String s="Sachin Tendulkar"; System.out.println(s.substring(6));//Tendulkar. System.out.println(s.substring(0,6));//Sachin. } } C:pgrs>java TestSubstring Tendulkar Sachin The java string substring() method returns a part of the string.
  • 18. STRINGS String comparison Can be done in 3 ways  equals() The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.  compareTo() 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. s1 == s2 : The method returns 0. s1 > s2 : The method returns a positive value.s1 < s2 : The method returns a negative value.  == Compare reference not the values. If the reference is not matched, it returns false. If all the reference is , it returns true.
  • 19. STRINGS String equals() import java.lang.String; public class EqualsExample{ public static void main(String args[]){ String s1=“reva"; String s2=“reva"; String s3=“REVA"; String s4="python"; System.out.println(s1.equals(s2));// true because content and case is same System.out.println(s1.equals(s3));// false because case is not same System.out.println(s1.equals(s4));// false because content is not same }} Output: true false false
  • 20. STRINGS String compareTo() class CompareToExample{ public static void main(String args[]){ String s1="hello"; String s2="hello"; String s3="meklo"; String s4="hemlo"; String s5="flag"; System.out.println(s1.compareTo(s2));//0 because both are equal System.out.println(s1.compareTo(s3));//5 because "h" is 5 times lower than "m" System.out.println(s1.compareTo(s4));//1 because "l" is 1 times lower than "m" System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f" }} C:pgrs>java CompareExam ple 0 -5 -1 2 t s r q p o n m l k j i h g f e d c b a
  • 21. STRINGS String == class Teststringcomparison4 { public static void main(String args[]){ String s1=“Reva"; String s2=“Reva"; String s3=“University"; String s4=new String(“Reva”); System.out.println(s1==s2); System.out.println(s1==s3) System.out.println(s1==s4) } } Output: true false false
  • 23. import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to REVA"); System.out.print("Return Value :"); System.out.println(Str.toLowerCase()); } } Output Return Value :welcome to reva STRINGS String toLowerCase() Method Syntax: public String toLowerCase()
  • 24. import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to reva"); System.out.print("Return Value :" ); System.out.println(Str.toUpperCase() ); } } Output Return Value :WELCOME TO REVA STRINGS String toUpperCase() Method Syntax: public String toUpperCase()
  • 25. public class CharAtExample { public static void main(String args[]) { String name=“REVA UNIVERSITY”; char ch=name.charAt(5); System.out.println(ch); } } Output: U STRINGS Java String charAt() Syntax: public char charAt(int index)
  • 26. public class LengthE { public static void main(String args[]) { String s1=“corona virus"; String s2=“India"; System.out.println("string length is: "+s1.length()); System.out.println("string length is: "+s2.length()); } } Output: string length is: 12 string length is: 5 STRINGS Java String length() Syntax: public int length()
  • 27. public class replaceE { public static void main(String args[]) { String s1=“St_y Home Stay S_fe"; String replaceString=s1.replace(‘_',‘a'); System.out.println(replaceString); } } Output: Stay Home Stay Safe STRINGS Java String replace() Syntax: public String replace(char oldChar, char newChar)
  • 28. public class trimE { public static void main(String args[]) { String s1=" REVA "; System.out.println(s1+"Bangalore"); System.out.println(s1.trim()+"Bangalore"); } } Output: C:pgrs>java trimE REVA Bangalore REVABangalore STRINGS Java String trim() that eliminates leading and trailing spaces Syntax: public String trim()
  • 29. public class SplitE { public static void main(String args[]) { String s1="REVA University best educational institute"; String[] words=s1.split(“ "); for(String w:words) { System.out.println(w); } } } Output: REVA University best educational Institute STRINGS Java String split() Syntax: public String split(String regex) •
  • 30. class Main { public static void main(String[] args) { String s1="REVA_University_best_educational_institute"; String[] words=s1.split("_",1); for(String w:words) { System.out.println(w); } } } Output: REVA_University_best_educational_institute STRINGS Java String split() Syntax: public String split(String regex) •
  • 31. class Main { public static void main(String[] args) { String s1="REVA_University_best_educational_institute"; String[] words=s1.split("_",3); for(String w:words) { System.out.println(w); } } } Output: REVA University best_educational_institute STRINGS Java String split() Syntax: public String split(String regex) •
  • 32. class containsE { public static void main(String args[]) { String name="what do you know about me"; System.out.println(name.contains("do you")); System.out.println(name.contains("about")); System.out.println(name.contains("hello")); } } Output: true true false STRINGS Java String contains() Syntax: public boolean contains(CharSequence sequence) •
  • 33. public class IsEmptyE { public static void main(String args[]) { String s1=""; String s2=“COVID-19"; System.out.println(s1.isEmpty()); System.out.println(s2.isEmpty()); } } Output: true false STRINGS Java String isEmpty() Syntax: public boolean isEmpty() •
  • 34. public class IsEmptyExample { public static void main(String args[]){ String s1=""; String s2="javatpoint"; System.out.println(s1.isEmpty()); System.out.println(s2.isEmpty()); }} Output: true false STRINGS Java String isEmpty() Syntax: public boolean isEmpty() •
  • 35. CHARSEQUENCE INTERFACE CharSequence Interface is used for representing the sequence of Characters in Java. 1. String 2. StringBuffer 3. StringBuilder
  • 36. 1. STRING String is an immutable class which means a constant and cannot be changed once created and if wish to change , we need to create an new object and even the functionality it provides like toupper, tolower, etc all these return a new object , its not modify the original object. It is automatically thread safe. String str= "geeks"; or String str= new String("geeks")
  • 37. 2. STRINGBUFFER • String represents fixed-length, immutable character sequences • StringBuffer represents growable and writable character sequences means it is immutable in nature • It is thread safe class , we can use it when we have multi threaded environment and shared object of string buffer i.e, used by mutiple thread. • Allow you to modify the contents of a string without creating a new object every time. • Syntax: StringBuffer demoString = new StringBuffer(“REVA");
  • 38. METHODS OF STRINGBUFFER 1. The initial capacity of a StringBuffer can be specified when it is created, or it can be set later with the ensureCapacity() method. 2. The append() method is used to add characters, strings, or other objects to the end of the buffer. 3. The insert() method is used to insert characters, strings, or other objects at a specified position in the buffer. 4. The delete() method is used to remove characters from the buffer. 5. The reverse() method is used to reverse the order of the characters in the buffer.
  • 39. public class StringBufferExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer ("Hello"); sb.append("Java"); // now original string is changed System.out.println(sb); sb.insert(1, "Java"); // Now original string is changed System.out.println(sb); sb.replace(1, 3, “REVA");// replaces the given string from the specified beginIndex and endIndex-1 System.out.println(sb); sb.delete(1, 3); System.out.println(sb); sb.reverse(); System.out.println(sb); StringBuffer sb1 = new StringBuffer(); System.out.println(“Default capacity is:"+sb1.capacity());//default 16 sb1.append("java is my favourite language"); System.out.println(sb1.capacity());// now it becomes (16*2)+2=34 } } Output: HelloJava HJavaelloJava HREVAvaelloJava HVAvaelloJava avaJolleavAVH Default capacity is:16 34
  • 40. STRINGBUILDER • StringBuilder in Java represents a mutable sequence of characters • As it creates a mutable sequence of characters and it is not thread safe and its used only within the thread. • It is mainly used for single threaded program. • The StringBuilder class differs from the StringBuffer class on the basis of synchronization. • The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer class does. Therefore this class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single thread • Syntax: StringBuilder demoString = new StringBuilder(); demoString.append(“REVA");
  • 41. public class StringBuilderExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(" "); sb.append("world!"); System.out.println(sb.toString()); // Output: "Hello world!" sb.insert(6, "beautiful "); System.out.println(sb.toString()); // Output: "Hello beautiful world!" sb.reverse(); System.out.println(sb.toString()); // Output: "!dlrow lufituaeb olleH" } Output: Hello world! Hello beautiful world! !dlrow lufituaeb olleH
  • 42. CREATING IMMUTABLE CLASS There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given below:
  • 43. public final class Employee { final String pancardNumber; public Employee(String pancardNumber) { this.pancardNumber=pancardNumber; } public String getPancardNumber() { return pancardNumber; } } public class ImmutableDemo { public static void main(String ar[]) { Employee e = new Employee("ABC123"); String s1 = e.getPancardNumber(); System.out.println("Pancard Number: " + s1); } } Output: Pancard Number: ABC123
  • 44. TO STRING () • 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. depending on your implementation.
  • 45. WITHOUT USING TOSTRING() METHOD class Student{ int rollno; String name, city; Student(int rollno, String name, String city){ this.rollno=rollno; this.name=name; this.city=city; } public static void main(String args[]){ Student s1=new Student(101,“ABC",“Bangalore"); Student s2=new Student(102,“XYZ",“Mysore"); System.out.println(s1);//compiler writes here s1.toString() System.out.println(s2);//compiler writes here s2.toString() } } Output: Student@1fee6fc Student@1eed786
  • 46. WITH USING TOSTRING() METHOD class Student { int rollno; String name, city; Student(int rollno, String name, String city) { this.rollno=rollno; this.name=name; this.city=city; } public String toString() {//overriding the toString() method return rollno+" "+name+" "+city; } public static void main(String args[]) { Student s1=new Student(101,“ABC",“Bangalore"); Student s2=new Student(102,“XYZ",“Mysore"); System.out.println(s1);//compiler writes here s1.toString() System.out.println(s2);//compiler writes here s2.toString() } } 101 ABC Bangalore 102 XYZ Mysore
  • 47. STRIGTOKENIZER CLASS • StringTokenizer class in Java is used to break a string into tokens. • The java.util.StringTokenizer class allows you to break a String into tokens. • In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens. Constructor Description StringTokenizer(String str) It creates StringTokenizer with specified string. StringTokenizer(String str, String delim) It creates StringTokenizer with specified string and delimiter. StringTokenizer(String str, String delim, boolean returnValue) It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.
  • 48. METHODS OF STRIGTOKENIZER CLASS Methods Description boolean hasMoreTokens() It checks if there is more tokens available. String nextToken() It returns the next token from the StringTokenizer object. String nextToken(String delim) It returns the next token based on the delimiter. boolean hasMoreElements() It is the same as hasMoreTokens() method. Object nextElement() It is the same as nextToken() but its return type is Object. int countTokens() It returns the total number of tokens.
  • 49. import java.util.StringTokenizer; public class StringTokenizer1 { public static void main(String args[]) { StringTokenizer st = new StringTokenizer("Demonstrating methods from Stri ngTokenizer class"," "); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } } Output: Demonstrating methods from StringTokenizer class