SlideShare a Scribd company logo
3
Most read
7
Most read
12
Most read
String Class :
 String represent a sequence of character.
 The String class belongs to the java.lang package, which
does not require an import statement.
 Sequence of character is represented in java is by using
a character array
char charArray[ ] = new char[4]
charArray[0]= ‘J’;
charArray[1]= ‘a’;
charArray[2]= ‘v’;
charArray[3]= ‘a’;
1 RAJESHREE KHANDE
String Class
X[0]
X[1]
X[2]
X[2][2]
X[1][3]
X[0][1]
Variable Size Array
2RAJESHREE KHANDE
String Class
 Character array not good enough to support the range
of operations we may like to perform on the string.
 In java String are class object & implemented using
two classes namely Sting & StringBuffer.
 A java string is an instantiated object of String Class.
 Java string is not character array & is not NULL
terminated.
 Strings are Immutable.
3 RAJESHREE KHANDE
String Class
String stringName = new String(“string”);
e.g.
String name = new String(“Rajeshree”);
To find the length of String length method of
string class is used.
int m = name.length();
4 RAJESHREE KHANDE
String Array
 We can also create & use array that contain
strings.
String itemArray[] = new String[3];
We can assign the element to this array by using
for loop.
5 RAJESHREE KHANDE
Literal Strings
 String literals are anonymous objects of the String class.
 are defined by enclosing text in double quotes. “This is a
literal String”
 don’t have to be constructed.
 can be assigned to String variables.
 can be passed to methods and constructors as
parameters.
6 RAJESHREE KHANDE
Literal String examples
String name = “Robert”;
//calling a method on a literal String
char firstInitial=“Robert”.charAt(0);
//calling a method on a String variable
char firstInitial = name.charAt(0);
7 RAJESHREE KHANDE
Empty Strings
 An empty String has no characters. It’s
length is 0.
 Not the same as an uninitialized String.
String word1 = “ ”;
String word2 = new String();
private String errorMsg; errorMsg
is null
Empty strings
8 RAJESHREE KHANDE
String Methods : Changing Case
 toLowerCase : Convert String to lowercase
 toUpperCase : Convert String to uppercase
String word2 = word1.toUpperCase();
String word3 = word1.toLowerCase();
 returns a new string formed from word1 by converting its
characters to upper (lower) case
String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); //”HELLO”
String word3 = word1.toLowerCase(); //”hello”
//word1 is still “HeLLo“
9 RAJESHREE KHANDE
String Methods : Changing Case
word1
remains
unchanged
 Example: to “convert” word1 to upper case, replace
the reference with a new reference.
 A common bug:
word1 = word1.toUpperCase();
word1.toUpperCase();
10 RAJESHREE KHANDE
String Methods : length, chatAt
 ”Problem".length();
 ”Window".charAt (2);
int length();
char charAt(i);
 Returns the number of characters in
the string
 Returns the char at position i.
7
’n'
Returns:
Character positions in strings are numbered
starting from 0 – just like arrays.
11 RAJESHREE KHANDE
String Methods : substring
television
i k
“lev"
“mutable"
"" (empty string)
”television".substring (2,5);
“immutable".substring (2);
“bob".substring (9);
television
i
 String subs = word.substring (i, k);
 returns the substring of chars in positions
from i to k-1
 String subs = word.substring (i);
 returns the substring from the i-th char to
the end
Returns a new String by copying characters from an existing String.
12 RAJESHREE KHANDE
String Methods : concat
String word1 = “re”, word2 = “think”; word3 = “ing”;
int num = 2;
String result = word1 + word2;
//concatenates word1 and word2 “rethink“
String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
result += word3;
//concatenates word3 to result “rethinking”
result += num; //converts num to String
//and concatenates it to result “rethinking2”
13 RAJESHREE KHANDE
String Methods : indexOf
String name =“President George Washington";
name.indexOf (‘P'); 0
name.indexOf (‘e'); 2
name.indexOf (“George"); 10
name.indexOf (‘e', 3); 6
name.indexOf (“Bob"); -1
name.lastIndexOf (‘e'); 15
0 2 6 10 15
(starts searching
at position 3)
(not found)
Returns:
14 RAJESHREE KHANDE
String Methods : Equality
boolean b = word1.equals(word2);
 returns true if the string word1 is equal to word2
boolean b = word1.equalsIgnoreCase(word2);
 returns true if the string word1 matches word2,
case
b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true
if(“team”.equalsIgnoreCase(“raiders”))
System.out.println(“Go You ” + “team”);
15 RAJESHREE KHANDE
String Methods : Comparisons
S1.compareTo(S2) : Return negative if S1<S2, positive if S1>S2,
zero if s1 equal to S2
int diff = word1.compareTo(word2);
int diff = word1.compareToIgnoreCase(word2);
Usually programmers don’t care what the numerical
“difference” of word1 - word2 is, just whether the difference
is negative (word1 comes before word2), zero (word1 and
word2 are equal) or positive (word1 comes after word2).
Often used in conditional statements.
if(word1.compareTo(word2) > 0){
//word1 comes after word2…
}
16 RAJESHREE KHANDE
Comparisons :Eaxmples
//negative differences
diff = “apple”.compareTo(“berry”); //a before b
diff = “Zebra”.compareTo(“apple”); //Z before a
diff = “dig”.compareTo(“dug”); //i before u
diff = “dig”.compareTo(“digs”); //dig is shorter
//zero differences
diff = “apple”.compareTo(“apple”); //equal
diff = “dig”.compareToIgnoreCase(“DIG”);/ /equal
//positive differences
diff = “berry”.compareTo(“apple”); //b after a
diff = “apple”.compareTo(“Apple”); //a after A
diff = “BIT”.compareTo(“BIG”); //T after G
diff = “huge”.compareTo(“hug”); //huge is longer
17 RAJESHREE KHANDE
String Methods : trim
s2 = s1.trim();
Removes white spaces at the beginning & at the end of string s1
 String word2 = word1.trim ();
 returns a new string formed from word1 by removing white
space at both end does not affect whites space in the middle
String word1 = “ Hi Bob ”;
String word2 = word1.trim();
//word2 is “Hi Bob” – no spaces on either end
//word1 is still “ Hi Bob “ – with spaces
18 RAJESHREE KHANDE
String Methods : replace
 String word2 = word1.replace(‘x’, ‘y’);
returns a new string formed from word1 by replacing
all occurrences of x with y
String word1 = “rare“;
String word2 = “rare“.replace(‘r’, ‘d’);
//word2 is “dade”, but word1 is still “rare“
19 RAJESHREE KHANDE
Numbers to Strings
Three ways to convert a number into a string:
1. String s = "" + num;
2. String s = Integer.toString (i);
String s = Double.toString (d);
3. String s = String.valueOf (num);
Integer and Double
are “wrapper” classes
from java.lang that
represent numbers as
objects. They also
provide useful static
methods.
s = String.valueOf(123) ; //”123”
s = “” + 123;//”123”
s = Integer.toString(123);
//”123”
s = Double.toString(3.14);
//”3.14”
20 RAJESHREE KHANDE
StringBuffer class
 StringBuffer is mutable object.
 The StringBuffer class is an alternative to the String
class.
 StringBuffer is more flexible than String. You can add,
insert, or append new contents into a string buffer.
21 RAJESHREE KHANDE
StringBuffer : Methods
Method Description
s1.setCharAt(n, x) Modifies the nth char to x of string s1
s1.append(s2) Append the string s2 to s1 at the end
s1.insert(n,s2) Insert the string s2 at the position n of string s1
s1.setLength(n) Set the length of the string s1 to n
If n < s1,length() s1 is truncated.
If n > s1.length zeros are added to s1
s1.deleteCharAt(n) Delete nth character from string s1
22RAJESHREE KHANDE

More Related Content

PDF
Java variable types
PPT
Java basic
PPTX
Object Oriented Programming with C#
PPT
Object Oriented Programming with Java
PPTX
This keyword in java
PPT
Java And Multithreading
PPTX
Java tokens
PPT
12 multi-threading
 
Java variable types
Java basic
Object Oriented Programming with C#
Object Oriented Programming with Java
This keyword in java
Java And Multithreading
Java tokens
12 multi-threading
 

What's hot (20)

PPTX
Java string handling
PPT
Final keyword in java
PPTX
Type casting in java
PPSX
Data Types & Variables in JAVA
PPTX
SUBQUERIES.pptx
PPTX
String, string builder, string buffer
PDF
Java IO
PPTX
Java basics and java variables
PPTX
Interfaces in java
PPTX
Arrays in java
PPT
Array in Java
PDF
Java arrays
PPT
Java Programming for Designers
PPTX
String Builder & String Buffer (Java Programming)
PPTX
Java packages
PDF
Constants, Variables and Data Types in Java
PPTX
Constructor in java
PPT
Core java concepts
PPT
Abstract class in java
Java string handling
Final keyword in java
Type casting in java
Data Types & Variables in JAVA
SUBQUERIES.pptx
String, string builder, string buffer
Java IO
Java basics and java variables
Interfaces in java
Arrays in java
Array in Java
Java arrays
Java Programming for Designers
String Builder & String Buffer (Java Programming)
Java packages
Constants, Variables and Data Types in Java
Constructor in java
Core java concepts
Abstract class in java
Ad

Similar to Java String class (20)

PPT
Strings in javamnjn ijnjun oinoin oinoi .ppt
PPT
Strings.ppt
PPTX
L13 string handling(string class)
PPTX
String Method.pptx
PPTX
Introduction to Java Strings, By Kavita Ganesan
PDF
java.lang.String Class
PPTX
DOC-20240802-WA0004dgcuhfgbjhfucjv6du..pptx
PDF
Module-1 Strings Handling.ppt.pdf
PPTX
Java String Handling
PDF
Strings in java
PPT
Charcater and Strings.ppt Charcater and Strings.ppt
PPT
Java căn bản - Chapter9
PDF
11-ch04-3-strings.pdf
PPT
Chapter 9 - Characters and Strings
PPT
Eo gaddis java_chapter_08_5e
PPT
Eo gaddis java_chapter_08_5e
PPT
Java Strings methods and operations.ppt
PPTX
Java Strings.pptxJava Strings.pptxJava Strings.pptx
PPS
String and string buffer
PPTX
String functions
Strings in javamnjn ijnjun oinoin oinoi .ppt
Strings.ppt
L13 string handling(string class)
String Method.pptx
Introduction to Java Strings, By Kavita Ganesan
java.lang.String Class
DOC-20240802-WA0004dgcuhfgbjhfucjv6du..pptx
Module-1 Strings Handling.ppt.pdf
Java String Handling
Strings in java
Charcater and Strings.ppt Charcater and Strings.ppt
Java căn bản - Chapter9
11-ch04-3-strings.pdf
Chapter 9 - Characters and Strings
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
Java Strings methods and operations.ppt
Java Strings.pptxJava Strings.pptxJava Strings.pptx
String and string buffer
String functions
Ad

More from DrRajeshreeKhande (20)

PPTX
.NET F# Inheritance and operator overloading
PPTX
Exception Handling in .NET F#
PPTX
.NET F# Events
PPTX
.NET F# Class constructor
PPTX
.NET F# Abstract class interface
PPTX
.Net F# Generic class
PPTX
F# Console class
PPTX
.net F# mutable dictionay
PPTX
F sharp lists & dictionary
PPTX
F# array searching
PPTX
Net (f#) array
PPTX
.Net (F # ) Records, lists
PPT
MS Office for Beginners
PPSX
Java Multi-threading programming
PPTX
JAVA AWT components
PPSX
Dr. Rajeshree Khande :Introduction to Java AWT
PPSX
Dr. Rajeshree Khande Java Interactive input
PPSX
Dr. Rajeshree Khande :Intoduction to java
PPSX
Java Exceptions Handling
PPSX
Dr. Rajeshree Khande : Java Basics
.NET F# Inheritance and operator overloading
Exception Handling in .NET F#
.NET F# Events
.NET F# Class constructor
.NET F# Abstract class interface
.Net F# Generic class
F# Console class
.net F# mutable dictionay
F sharp lists & dictionary
F# array searching
Net (f#) array
.Net (F # ) Records, lists
MS Office for Beginners
Java Multi-threading programming
JAVA AWT components
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande :Intoduction to java
Java Exceptions Handling
Dr. Rajeshree Khande : Java Basics

Recently uploaded (20)

PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Business Ethics Teaching Materials for college
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Basic Mud Logging Guide for educational purpose
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Open folder Downloads.pdf yes yes ges yes
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
English Language Teaching from Post-.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Business Ethics Teaching Materials for college
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
Renaissance Architecture: A Journey from Faith to Humanism
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
human mycosis Human fungal infections are called human mycosis..pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Week 4 Term 3 Study Techniques revisited.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Basic Mud Logging Guide for educational purpose
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
NOI Hackathon - Summer Edition - GreenThumber.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Open folder Downloads.pdf yes yes ges yes
Open Quiz Monsoon Mind Game Final Set.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
O5-L3 Freight Transport Ops (International) V1.pdf
English Language Teaching from Post-.pdf
O7-L3 Supply Chain Operations - ICLT Program

Java String class

  • 1. String Class :  String represent a sequence of character.  The String class belongs to the java.lang package, which does not require an import statement.  Sequence of character is represented in java is by using a character array char charArray[ ] = new char[4] charArray[0]= ‘J’; charArray[1]= ‘a’; charArray[2]= ‘v’; charArray[3]= ‘a’; 1 RAJESHREE KHANDE
  • 3. String Class  Character array not good enough to support the range of operations we may like to perform on the string.  In java String are class object & implemented using two classes namely Sting & StringBuffer.  A java string is an instantiated object of String Class.  Java string is not character array & is not NULL terminated.  Strings are Immutable. 3 RAJESHREE KHANDE
  • 4. String Class String stringName = new String(“string”); e.g. String name = new String(“Rajeshree”); To find the length of String length method of string class is used. int m = name.length(); 4 RAJESHREE KHANDE
  • 5. String Array  We can also create & use array that contain strings. String itemArray[] = new String[3]; We can assign the element to this array by using for loop. 5 RAJESHREE KHANDE
  • 6. Literal Strings  String literals are anonymous objects of the String class.  are defined by enclosing text in double quotes. “This is a literal String”  don’t have to be constructed.  can be assigned to String variables.  can be passed to methods and constructors as parameters. 6 RAJESHREE KHANDE
  • 7. Literal String examples String name = “Robert”; //calling a method on a literal String char firstInitial=“Robert”.charAt(0); //calling a method on a String variable char firstInitial = name.charAt(0); 7 RAJESHREE KHANDE
  • 8. Empty Strings  An empty String has no characters. It’s length is 0.  Not the same as an uninitialized String. String word1 = “ ”; String word2 = new String(); private String errorMsg; errorMsg is null Empty strings 8 RAJESHREE KHANDE
  • 9. String Methods : Changing Case  toLowerCase : Convert String to lowercase  toUpperCase : Convert String to uppercase String word2 = word1.toUpperCase(); String word3 = word1.toLowerCase();  returns a new string formed from word1 by converting its characters to upper (lower) case String word1 = “HeLLo”; String word2 = word1.toUpperCase(); //”HELLO” String word3 = word1.toLowerCase(); //”hello” //word1 is still “HeLLo“ 9 RAJESHREE KHANDE
  • 10. String Methods : Changing Case word1 remains unchanged  Example: to “convert” word1 to upper case, replace the reference with a new reference.  A common bug: word1 = word1.toUpperCase(); word1.toUpperCase(); 10 RAJESHREE KHANDE
  • 11. String Methods : length, chatAt  ”Problem".length();  ”Window".charAt (2); int length(); char charAt(i);  Returns the number of characters in the string  Returns the char at position i. 7 ’n' Returns: Character positions in strings are numbered starting from 0 – just like arrays. 11 RAJESHREE KHANDE
  • 12. String Methods : substring television i k “lev" “mutable" "" (empty string) ”television".substring (2,5); “immutable".substring (2); “bob".substring (9); television i  String subs = word.substring (i, k);  returns the substring of chars in positions from i to k-1  String subs = word.substring (i);  returns the substring from the i-th char to the end Returns a new String by copying characters from an existing String. 12 RAJESHREE KHANDE
  • 13. String Methods : concat String word1 = “re”, word2 = “think”; word3 = “ing”; int num = 2; String result = word1 + word2; //concatenates word1 and word2 “rethink“ String result = word1.concat (word2); //the same as word1 + word2 “rethink“ result += word3; //concatenates word3 to result “rethinking” result += num; //converts num to String //and concatenates it to result “rethinking2” 13 RAJESHREE KHANDE
  • 14. String Methods : indexOf String name =“President George Washington"; name.indexOf (‘P'); 0 name.indexOf (‘e'); 2 name.indexOf (“George"); 10 name.indexOf (‘e', 3); 6 name.indexOf (“Bob"); -1 name.lastIndexOf (‘e'); 15 0 2 6 10 15 (starts searching at position 3) (not found) Returns: 14 RAJESHREE KHANDE
  • 15. String Methods : Equality boolean b = word1.equals(word2);  returns true if the string word1 is equal to word2 boolean b = word1.equalsIgnoreCase(word2);  returns true if the string word1 matches word2, case b = “Raiders”.equals(“Raiders”);//true b = “Raiders”.equals(“raiders”);//false b = “Raiders”.equalsIgnoreCase(“raiders”);//true if(“team”.equalsIgnoreCase(“raiders”)) System.out.println(“Go You ” + “team”); 15 RAJESHREE KHANDE
  • 16. String Methods : Comparisons S1.compareTo(S2) : Return negative if S1<S2, positive if S1>S2, zero if s1 equal to S2 int diff = word1.compareTo(word2); int diff = word1.compareToIgnoreCase(word2); Usually programmers don’t care what the numerical “difference” of word1 - word2 is, just whether the difference is negative (word1 comes before word2), zero (word1 and word2 are equal) or positive (word1 comes after word2). Often used in conditional statements. if(word1.compareTo(word2) > 0){ //word1 comes after word2… } 16 RAJESHREE KHANDE
  • 17. Comparisons :Eaxmples //negative differences diff = “apple”.compareTo(“berry”); //a before b diff = “Zebra”.compareTo(“apple”); //Z before a diff = “dig”.compareTo(“dug”); //i before u diff = “dig”.compareTo(“digs”); //dig is shorter //zero differences diff = “apple”.compareTo(“apple”); //equal diff = “dig”.compareToIgnoreCase(“DIG”);/ /equal //positive differences diff = “berry”.compareTo(“apple”); //b after a diff = “apple”.compareTo(“Apple”); //a after A diff = “BIT”.compareTo(“BIG”); //T after G diff = “huge”.compareTo(“hug”); //huge is longer 17 RAJESHREE KHANDE
  • 18. String Methods : trim s2 = s1.trim(); Removes white spaces at the beginning & at the end of string s1  String word2 = word1.trim ();  returns a new string formed from word1 by removing white space at both end does not affect whites space in the middle String word1 = “ Hi Bob ”; String word2 = word1.trim(); //word2 is “Hi Bob” – no spaces on either end //word1 is still “ Hi Bob “ – with spaces 18 RAJESHREE KHANDE
  • 19. String Methods : replace  String word2 = word1.replace(‘x’, ‘y’); returns a new string formed from word1 by replacing all occurrences of x with y String word1 = “rare“; String word2 = “rare“.replace(‘r’, ‘d’); //word2 is “dade”, but word1 is still “rare“ 19 RAJESHREE KHANDE
  • 20. Numbers to Strings Three ways to convert a number into a string: 1. String s = "" + num; 2. String s = Integer.toString (i); String s = Double.toString (d); 3. String s = String.valueOf (num); Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. They also provide useful static methods. s = String.valueOf(123) ; //”123” s = “” + 123;//”123” s = Integer.toString(123); //”123” s = Double.toString(3.14); //”3.14” 20 RAJESHREE KHANDE
  • 21. StringBuffer class  StringBuffer is mutable object.  The StringBuffer class is an alternative to the String class.  StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer. 21 RAJESHREE KHANDE
  • 22. StringBuffer : Methods Method Description s1.setCharAt(n, x) Modifies the nth char to x of string s1 s1.append(s2) Append the string s2 to s1 at the end s1.insert(n,s2) Insert the string s2 at the position n of string s1 s1.setLength(n) Set the length of the string s1 to n If n < s1,length() s1 is truncated. If n > s1.length zeros are added to s1 s1.deleteCharAt(n) Delete nth character from string s1 22RAJESHREE KHANDE