SlideShare a Scribd company logo
1 of 28
Download to read offline
Strings in Java
Dr. Kuppusamy .P
Associate Professor / SCOPE
Strings in Java
• String is a group of characters.
• They are objects of type String class.
• Once a String object is created it cannot be changed i.e.,
Immutable.
• String are declared as final, so there cannot be subclasses of these
classes.
• The default constructor creates an empty string.
String str = new String();
Dr. Kuppusamy P
Creating String
String s1 = “welcome”; //primitive type
equivalent to
String s2 = new String(“welcome”); //object type
or equivalent to
char data[] = {‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’}; //array type
String s3 = new String(data);
or equivalent to
String s4 = new String(s1); //reference type
Dr. Kuppusamy P
String class - Methods & Example
1. The length() method returns the length of the string.
Ex:
• System.out.println(“Hari".length());
• Output: 4.
2. The + operator is used to concatenate two or more strings.
Ex:
• String myName = “Kaven";
• String s = "My name is" + myName+ ".";
• For string concatenation, the Java compiler converts an operand to
a String whenever the other operand of the + is a String object.
Dr. Kuppusamy P
String class - Methods & Example
3. charAt() method.
Characters in a string can be retrieved in a number of ways.
public char charAt(int index)
• Method returns the character at the specified index.
• An index ranges from 0 to length()-1
char c;
c = "abc".charAt(1);
// Output :
c = ‘b’
Dr. Kuppusamy P
String class - Methods & Example
4. equals() Method
• It compares the Strings. It returns true, if the argument is not null and it contains
the same sequence of characters.
public boolean equals(anotherString);
String s1=“VIT-AP”;
String s2=“vit-AP”;
boolean result = s1.equals(s2); //false is the result
5. equalsIgnoreCase() Method
• Compares two Strings, ignoring case considerations..
public boolean equalsIgnoreCase(anotherString);
String s1=“VIT-AP”;
String s2=“vit-AP”;
boolean result = s1.equalsIgnoreCase(s2); //true is the result
Dr. Kuppusamy P
String class - Methods & Example
6. startsWith()
• Checks the String starts with the specified prefix.
public boolean startsWith(String prefix)
"January".startsWith("Jan");
// Output: true
7. endsWith()
• Checks the String ends with the specified suffix.
public boolean endsWith(String suffix)
"January".endsWith("ry");
// Output: true
Dr. Kuppusamy P
String class - Methods & Example
8. compareTo()
• Compares two strings and to know which string is bigger or smaller
• Returns negative integer, if this String object is less than the argument string
• Returns positive integer if this String object is greater than the argument string.
• return 0(zero), if these strings are equal.
public int compareTo(String anotherString)
9. public int compareToIgnoreCase(String str)
• This method is similar to compareTo() method, but this does not consider the
case of strings.
Dr. Kuppusamy P
String class - Methods & Example
10. indexOf() Method
• Searches for the first occurrence of a character or substring.
• Returns -1 if the character does not occur
public int indexOf(int ch)
• It searches for the character represented by ch within this string and returns the
index of first occurrence of this character
public int indexOf(String str)
• It searches for the substring specified by str within this string and returns the
index of first occurrence of this substring
Example:
String str = “How was your day today?”;
str.indexOf(‘t’); //17
str.indexOf(“was”); //4
Dr. Kuppusamy P
String class - Methods & Example
public int indexOf(int ch, int index)
• It searches for the character represented by ch within this String and returns the
index of first occurrence of this character starting from the position specified by
from index
public int indexOf(String str, int index)
• It searches for the substring represented by str within this String and returns the
index of first occurrence of this substring starting from the position specified by
from index
Example:
String str = “How was your day today?”;
str.indexOf(‘a’,6); //14
str.indexOf(“was”,2); //4
Dr. Kuppusamy P
String class - Methods & Example
11.lastIndexOf()
• It searches for the last occurrence of a particular character or substring
12. substring()
• This method returns a new string which is actually a substring of this string.
• It extracts characters starting from the specified index all the way till the end of
the string
public String substring(int beginIndex)
Eg:
“unhappy”.substring(2) returns “happy”
public String substring(int beginIndex, int endIndex)
Eg:
“smiles”.substring(1,5) returns “mile”
Dr. Kuppusamy P
String class - Methods & Example
13.concat()
• Concatenates the specified string to the end of this string
public String concat(String str)
"to".concat("get").concat("her") //return together
14.replace()
• Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar
public String replace(char oldChar, char newChar);
String str = "How was your day today?";
System.out.println(str.replace('a', '3'));
//displays How w3s your d3y tod3y?“
Dr. Kuppusamy P
String class - Methods & Example
15.trim()
• Returns a copy of the string, with leading and trailing whitespace omitted
public String trim()
String s = “Hi Mom! “.trim();
S = “Hi Mom!”
16. valueOf()
• This method is used to convert a character array into String.
• The result is a String representation of argument passed as character array
public static String valueOf (char[] data);
Dr. Kuppusamy P
String class - Methods & Example
valueOf()
This method is used to convert anything into String.
String s= String.valueOf(boolean b);
String s= String.valueOf(char c);
String s= String.valueOf(int i);
String s= String.valueOf(float f);
String s= String.valueOf(double d);
Dr. Kuppusamy P
String class - Methods & Example
17.toLowerCase():
• Converts all characters in a String to lower case
public String toLowerCase();
String s = “JaVa”.toLowerCase(); // java
18.toUpperCase():
• Converts characters in a String to upper case
public String toUpperCase();
String s = “JaVa”.toLowerCase(); // JAVA
Dr. Kuppusamy P
String class – Additional Methods
Dr. Kuppusamy P
String class - Methods & Example
19. split() method can split a String into n number of sub strings.
public String[] split(String regex)
Ex:
public class StringEx1{
public static void main(String [] args) {
String s="Welcome to VIT-AP";
String[] s1=s.split(" ");
for(String i:s1)
System.out.println(i);
}
}
Dr. Kuppusamy P
String class - Methods & Example
20. toCharArray() method can split a String into n number of characters.
public char[] toCharArray()
Ex.
public class StringEx2{
public static void main(String [] args) {
String s="Welcome";
char[] c=s.toCharArray();
for(char i:c)
System.out.println(i);
}
}
Dr. Kuppusamy P
String class - Methods & Example
21. contains() method used to check whether the given sub string is a part of
the other string.
public boolean contains(String s)
Ex.
public class StringEx3{
public static void main(String [] args) {
String s="VIT-AP";
if(s.contains("VIT"))
System.out.print("Welcome to VIT-AP");
}
}
Dr. Kuppusamy P
String class - Methods & Example
22. format() method used to format any data into specified format of string.
public static String format(String format, Object... args)
Ex.
String str1 = String.format("%d", 101); // Integer value
String str2 = String.format("%s", "Amar Singh"); // String value
String str3 = String.format("%f", 101.00); // Float value
String str4 = String.format("%2.2f", 101.14325); // Float value with 2 points
String str5 = String.format("%x", 10); // Hexadecimal value
String str6 = String.format("%c", 'c’); // Char value
Dr. Kuppusamy P
StringBuffer Class
and
StringBuffer Class Predefined Methods
Dr. Kuppusamy P
StringBuffer class
• String class is used to create a string of fixed length.
• But StringBuffer class creates strings of flexible length which can be
modified.
• StringBuffer class objects are mutable, so they can be changeable
• StringBuffer are declared as final.
• StringBuffer class defines three constructors:
1. StringBuffer()
• Creates empty object with initial capacity of 16 characters.
2. StringBuffer(int capacity)
• Creates an empty (no character in it) object with a given capacity
(not less than 0) for storing a string
3. StringBuffer(String str)
• Create StringBuffer object with string object.
• The initial capacity of the string buffer is 16, plus the length of the
string arguments.
• The value of str cannot be null,
Dr. Kuppusamy P
Create StringBuffer class
StringBuffer sb1=new StringBuffer();
StringBuffer sb2=new StringBuffer(5);
StringBuffer sb3=new StringBuffer("Welcome");
System.out.println(sb1.capacity()); // 16
System.out.println(sb1.length()); // 0
System.out.println(sb2.capacity()); // 10
System.out.println(sb2.length()); // 0
System.out.println(sb3.capacity()); // 23
System.out.println(sb3.length()); // 7
Dr. Kuppusamy P
StringBuffer Class Methods
1. append() method - Append any data type with the string.
public StringBuffer append(boolean b)
Ex:
StringBuffer sb3=new StringBuffer("Welcome");
sb3.append(" VIT-AP");
System.out.println(sb3); // Welcome VIT-AP
2. insert() - insert any data into string at any location.
public StringBuffer insert(int offset, int i)
Ex:
StringBuffer sb3=new StringBuffer("Welcome VIT-AP");
sb3.insert(8, “to”);
System.out.println(sb3);
Dr. Kuppusamy P
StringBuffer Class Methods
3. delete() method - deletes a sub string from the specified begin index to end
index
public StringBuffer delete(int start, int end)
Ex:
StringBuffer sb3=new StringBuffer("Welcome VIT-AP");
sb3.insert(8, “to”);
System.out.println(sb3); // Welcome to VIT-AP
sb3.delete(8, 16);
System.out.println(sb3); // Welcome
Dr. Kuppusamy P
StringBuffer Class Methods
4. replace() –replaces part of this StringBuffer(substring) with another substring
public StringBuffer replace(int start, int end, String str);
Ex:
StringBuffer sb3=new StringBuffer("Welcome");
sb3.replace(3, 7, "done");
System.out.println(sb3); // Weldone
5. reverse() –reverses the StringBuffer and store it in the same StringBuffer
object.
public StringBuffer replace(int start, int end, String str);
Ex:
StringBuffer sb3=new StringBuffer("Welcome");
sb3.reverse();
System.out.println(sb3); // emocleW
Dr. Kuppusamy P
StringBuffer Class Methods
6. tostring() – Represents the object of StringBuffer class into String
StringBuffer sb3=new StringBuffer("Welcome");
sb3.reverse();
String s=sb3.toString();
System.out.println(s);
Dr. Kuppusamy P
References
Dr. Kuppusamy P
Herbert Schildt, “Java: The Complete Reference”, McGraw-Hill Education, Tenth edition,
2017.

More Related Content

What's hot

Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java Janu Jahnavi
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in JavaJava2Blog
 
Java variable types
Java variable typesJava variable types
Java variable typesSoba Arjun
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptxmaryansagsgao
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda FunctionMd Soyaib
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanKavita Ganesan
 
virtual function
virtual functionvirtual function
virtual functionVENNILAV6
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaRahulAnanda1
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaAtul Sehdev
 

What's hot (20)

Java arrays
Java arraysJava arrays
Java arrays
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
 
Java variable types
Java variable typesJava variable types
Java variable types
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptx
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda Function
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
virtual function
virtual functionvirtual function
virtual function
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 

Similar to Strings in java

Similar to Strings in java (20)

Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
Strings
StringsStrings
Strings
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
 
8. String
8. String8. String
8. String
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
 
M C6java7
M C6java7M C6java7
M C6java7
 
07slide
07slide07slide
07slide
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
Team 1
Team 1Team 1
Team 1
 
StringBuffer.pptx
StringBuffer.pptxStringBuffer.pptx
StringBuffer.pptx
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 
Text processing
Text processingText processing
Text processing
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Python data handling
Python data handlingPython data handling
Python data handling
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 

More from Kuppusamy P

Recurrent neural networks rnn
Recurrent neural networks   rnnRecurrent neural networks   rnn
Recurrent neural networks rnnKuppusamy P
 
Image segmentation
Image segmentationImage segmentation
Image segmentationKuppusamy P
 
Image enhancement
Image enhancementImage enhancement
Image enhancementKuppusamy P
 
Feature detection and matching
Feature detection and matchingFeature detection and matching
Feature detection and matchingKuppusamy P
 
Image processing, Noise, Noise Removal filters
Image processing, Noise, Noise Removal filtersImage processing, Noise, Noise Removal filters
Image processing, Noise, Noise Removal filtersKuppusamy P
 
Flowchart design for algorithms
Flowchart design for algorithmsFlowchart design for algorithms
Flowchart design for algorithmsKuppusamy P
 
Algorithm basics
Algorithm basicsAlgorithm basics
Algorithm basicsKuppusamy P
 
Problem solving using Programming
Problem solving using ProgrammingProblem solving using Programming
Problem solving using ProgrammingKuppusamy P
 
Parts of Computer, Hardware and Software
Parts of Computer, Hardware and Software Parts of Computer, Hardware and Software
Parts of Computer, Hardware and Software Kuppusamy P
 
Java methods or Subroutines or Functions
Java methods or Subroutines or FunctionsJava methods or Subroutines or Functions
Java methods or Subroutines or FunctionsKuppusamy P
 
Java iterative statements
Java iterative statementsJava iterative statements
Java iterative statementsKuppusamy P
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
Java introduction
Java introductionJava introduction
Java introductionKuppusamy P
 
Logistic regression in Machine Learning
Logistic regression in Machine LearningLogistic regression in Machine Learning
Logistic regression in Machine LearningKuppusamy P
 
Anomaly detection (Unsupervised Learning) in Machine Learning
Anomaly detection (Unsupervised Learning) in Machine LearningAnomaly detection (Unsupervised Learning) in Machine Learning
Anomaly detection (Unsupervised Learning) in Machine LearningKuppusamy P
 
Machine Learning Performance metrics for classification
Machine Learning Performance metrics for classificationMachine Learning Performance metrics for classification
Machine Learning Performance metrics for classificationKuppusamy P
 
Machine learning Introduction
Machine learning IntroductionMachine learning Introduction
Machine learning IntroductionKuppusamy P
 
Reinforcement learning, Q-Learning
Reinforcement learning, Q-LearningReinforcement learning, Q-Learning
Reinforcement learning, Q-LearningKuppusamy P
 

More from Kuppusamy P (20)

Recurrent neural networks rnn
Recurrent neural networks   rnnRecurrent neural networks   rnn
Recurrent neural networks rnn
 
Deep learning
Deep learningDeep learning
Deep learning
 
Image segmentation
Image segmentationImage segmentation
Image segmentation
 
Image enhancement
Image enhancementImage enhancement
Image enhancement
 
Feature detection and matching
Feature detection and matchingFeature detection and matching
Feature detection and matching
 
Image processing, Noise, Noise Removal filters
Image processing, Noise, Noise Removal filtersImage processing, Noise, Noise Removal filters
Image processing, Noise, Noise Removal filters
 
Flowchart design for algorithms
Flowchart design for algorithmsFlowchart design for algorithms
Flowchart design for algorithms
 
Algorithm basics
Algorithm basicsAlgorithm basics
Algorithm basics
 
Problem solving using Programming
Problem solving using ProgrammingProblem solving using Programming
Problem solving using Programming
 
Parts of Computer, Hardware and Software
Parts of Computer, Hardware and Software Parts of Computer, Hardware and Software
Parts of Computer, Hardware and Software
 
Java methods or Subroutines or Functions
Java methods or Subroutines or FunctionsJava methods or Subroutines or Functions
Java methods or Subroutines or Functions
 
Java iterative statements
Java iterative statementsJava iterative statements
Java iterative statements
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Java data types
Java data typesJava data types
Java data types
 
Java introduction
Java introductionJava introduction
Java introduction
 
Logistic regression in Machine Learning
Logistic regression in Machine LearningLogistic regression in Machine Learning
Logistic regression in Machine Learning
 
Anomaly detection (Unsupervised Learning) in Machine Learning
Anomaly detection (Unsupervised Learning) in Machine LearningAnomaly detection (Unsupervised Learning) in Machine Learning
Anomaly detection (Unsupervised Learning) in Machine Learning
 
Machine Learning Performance metrics for classification
Machine Learning Performance metrics for classificationMachine Learning Performance metrics for classification
Machine Learning Performance metrics for classification
 
Machine learning Introduction
Machine learning IntroductionMachine learning Introduction
Machine learning Introduction
 
Reinforcement learning, Q-Learning
Reinforcement learning, Q-LearningReinforcement learning, Q-Learning
Reinforcement learning, Q-Learning
 

Recently uploaded

Slides CapTechTalks Webinar March 2024 Joshua Sinai.pptx
Slides CapTechTalks Webinar March 2024 Joshua Sinai.pptxSlides CapTechTalks Webinar March 2024 Joshua Sinai.pptx
Slides CapTechTalks Webinar March 2024 Joshua Sinai.pptxCapitolTechU
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...raviapr7
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 
3.26.24 Race, the Draft, and the Vietnam War.pptx
3.26.24 Race, the Draft, and the Vietnam War.pptx3.26.24 Race, the Draft, and the Vietnam War.pptx
3.26.24 Race, the Draft, and the Vietnam War.pptxmary850239
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptxmary850239
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICESayali Powar
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17Celine George
 
How to Create a Toggle Button in Odoo 17
How to Create a Toggle Button in Odoo 17How to Create a Toggle Button in Odoo 17
How to Create a Toggle Button in Odoo 17Celine George
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsEugene Lysak
 
A gentle introduction to Artificial Intelligence
A gentle introduction to Artificial IntelligenceA gentle introduction to Artificial Intelligence
A gentle introduction to Artificial IntelligenceApostolos Syropoulos
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxheathfieldcps1
 
Riddhi Kevadiya. WILLIAM SHAKESPEARE....
Riddhi Kevadiya. WILLIAM SHAKESPEARE....Riddhi Kevadiya. WILLIAM SHAKESPEARE....
Riddhi Kevadiya. WILLIAM SHAKESPEARE....Riddhi Kevadiya
 
Department of Health Compounder Question ‍Solution 2022.pdf
Department of Health Compounder Question ‍Solution 2022.pdfDepartment of Health Compounder Question ‍Solution 2022.pdf
Department of Health Compounder Question ‍Solution 2022.pdfMohonDas
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...CaraSkikne1
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxiammrhaywood
 

Recently uploaded (20)

Slides CapTechTalks Webinar March 2024 Joshua Sinai.pptx
Slides CapTechTalks Webinar March 2024 Joshua Sinai.pptxSlides CapTechTalks Webinar March 2024 Joshua Sinai.pptx
Slides CapTechTalks Webinar March 2024 Joshua Sinai.pptx
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 
3.26.24 Race, the Draft, and the Vietnam War.pptx
3.26.24 Race, the Draft, and the Vietnam War.pptx3.26.24 Race, the Draft, and the Vietnam War.pptx
3.26.24 Race, the Draft, and the Vietnam War.pptx
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
3.21.24 The Origins of Black Power.pptx
3.21.24  The Origins of Black Power.pptx3.21.24  The Origins of Black Power.pptx
3.21.24 The Origins of Black Power.pptx
 
Quality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICEQuality Assurance_GOOD LABORATORY PRACTICE
Quality Assurance_GOOD LABORATORY PRACTICE
 
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdfPersonal Resilience in Project Management 2 - TV Edit 1a.pdf
Personal Resilience in Project Management 2 - TV Edit 1a.pdf
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
March 2024 Directors Meeting, Division of Student Affairs and Academic Support
March 2024 Directors Meeting, Division of Student Affairs and Academic SupportMarch 2024 Directors Meeting, Division of Student Affairs and Academic Support
March 2024 Directors Meeting, Division of Student Affairs and Academic Support
 
How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17How to Show Error_Warning Messages in Odoo 17
How to Show Error_Warning Messages in Odoo 17
 
How to Create a Toggle Button in Odoo 17
How to Create a Toggle Button in Odoo 17How to Create a Toggle Button in Odoo 17
How to Create a Toggle Button in Odoo 17
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George Wells
 
A gentle introduction to Artificial Intelligence
A gentle introduction to Artificial IntelligenceA gentle introduction to Artificial Intelligence
A gentle introduction to Artificial Intelligence
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
Riddhi Kevadiya. WILLIAM SHAKESPEARE....
Riddhi Kevadiya. WILLIAM SHAKESPEARE....Riddhi Kevadiya. WILLIAM SHAKESPEARE....
Riddhi Kevadiya. WILLIAM SHAKESPEARE....
 
Department of Health Compounder Question ‍Solution 2022.pdf
Department of Health Compounder Question ‍Solution 2022.pdfDepartment of Health Compounder Question ‍Solution 2022.pdf
Department of Health Compounder Question ‍Solution 2022.pdf
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
 

Strings in java

  • 1. Strings in Java Dr. Kuppusamy .P Associate Professor / SCOPE
  • 2. Strings in Java • String is a group of characters. • They are objects of type String class. • Once a String object is created it cannot be changed i.e., Immutable. • String are declared as final, so there cannot be subclasses of these classes. • The default constructor creates an empty string. String str = new String(); Dr. Kuppusamy P
  • 3. Creating String String s1 = “welcome”; //primitive type equivalent to String s2 = new String(“welcome”); //object type or equivalent to char data[] = {‘w’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’}; //array type String s3 = new String(data); or equivalent to String s4 = new String(s1); //reference type Dr. Kuppusamy P
  • 4. String class - Methods & Example 1. The length() method returns the length of the string. Ex: • System.out.println(“Hari".length()); • Output: 4. 2. The + operator is used to concatenate two or more strings. Ex: • String myName = “Kaven"; • String s = "My name is" + myName+ "."; • For string concatenation, the Java compiler converts an operand to a String whenever the other operand of the + is a String object. Dr. Kuppusamy P
  • 5. String class - Methods & Example 3. charAt() method. Characters in a string can be retrieved in a number of ways. public char charAt(int index) • Method returns the character at the specified index. • An index ranges from 0 to length()-1 char c; c = "abc".charAt(1); // Output : c = ‘b’ Dr. Kuppusamy P
  • 6. String class - Methods & Example 4. equals() Method • It compares the Strings. It returns true, if the argument is not null and it contains the same sequence of characters. public boolean equals(anotherString); String s1=“VIT-AP”; String s2=“vit-AP”; boolean result = s1.equals(s2); //false is the result 5. equalsIgnoreCase() Method • Compares two Strings, ignoring case considerations.. public boolean equalsIgnoreCase(anotherString); String s1=“VIT-AP”; String s2=“vit-AP”; boolean result = s1.equalsIgnoreCase(s2); //true is the result Dr. Kuppusamy P
  • 7. String class - Methods & Example 6. startsWith() • Checks the String starts with the specified prefix. public boolean startsWith(String prefix) "January".startsWith("Jan"); // Output: true 7. endsWith() • Checks the String ends with the specified suffix. public boolean endsWith(String suffix) "January".endsWith("ry"); // Output: true Dr. Kuppusamy P
  • 8. String class - Methods & Example 8. compareTo() • Compares two strings and to know which string is bigger or smaller • Returns negative integer, if this String object is less than the argument string • Returns positive integer if this String object is greater than the argument string. • return 0(zero), if these strings are equal. public int compareTo(String anotherString) 9. public int compareToIgnoreCase(String str) • This method is similar to compareTo() method, but this does not consider the case of strings. Dr. Kuppusamy P
  • 9. String class - Methods & Example 10. indexOf() Method • Searches for the first occurrence of a character or substring. • Returns -1 if the character does not occur public int indexOf(int ch) • It searches for the character represented by ch within this string and returns the index of first occurrence of this character public int indexOf(String str) • It searches for the substring specified by str within this string and returns the index of first occurrence of this substring Example: String str = “How was your day today?”; str.indexOf(‘t’); //17 str.indexOf(“was”); //4 Dr. Kuppusamy P
  • 10. String class - Methods & Example public int indexOf(int ch, int index) • It searches for the character represented by ch within this String and returns the index of first occurrence of this character starting from the position specified by from index public int indexOf(String str, int index) • It searches for the substring represented by str within this String and returns the index of first occurrence of this substring starting from the position specified by from index Example: String str = “How was your day today?”; str.indexOf(‘a’,6); //14 str.indexOf(“was”,2); //4 Dr. Kuppusamy P
  • 11. String class - Methods & Example 11.lastIndexOf() • It searches for the last occurrence of a particular character or substring 12. substring() • This method returns a new string which is actually a substring of this string. • It extracts characters starting from the specified index all the way till the end of the string public String substring(int beginIndex) Eg: “unhappy”.substring(2) returns “happy” public String substring(int beginIndex, int endIndex) Eg: “smiles”.substring(1,5) returns “mile” Dr. Kuppusamy P
  • 12. String class - Methods & Example 13.concat() • Concatenates the specified string to the end of this string public String concat(String str) "to".concat("get").concat("her") //return together 14.replace() • Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar public String replace(char oldChar, char newChar); String str = "How was your day today?"; System.out.println(str.replace('a', '3')); //displays How w3s your d3y tod3y?“ Dr. Kuppusamy P
  • 13. String class - Methods & Example 15.trim() • Returns a copy of the string, with leading and trailing whitespace omitted public String trim() String s = “Hi Mom! “.trim(); S = “Hi Mom!” 16. valueOf() • This method is used to convert a character array into String. • The result is a String representation of argument passed as character array public static String valueOf (char[] data); Dr. Kuppusamy P
  • 14. String class - Methods & Example valueOf() This method is used to convert anything into String. String s= String.valueOf(boolean b); String s= String.valueOf(char c); String s= String.valueOf(int i); String s= String.valueOf(float f); String s= String.valueOf(double d); Dr. Kuppusamy P
  • 15. String class - Methods & Example 17.toLowerCase(): • Converts all characters in a String to lower case public String toLowerCase(); String s = “JaVa”.toLowerCase(); // java 18.toUpperCase(): • Converts characters in a String to upper case public String toUpperCase(); String s = “JaVa”.toLowerCase(); // JAVA Dr. Kuppusamy P
  • 16. String class – Additional Methods Dr. Kuppusamy P
  • 17. String class - Methods & Example 19. split() method can split a String into n number of sub strings. public String[] split(String regex) Ex: public class StringEx1{ public static void main(String [] args) { String s="Welcome to VIT-AP"; String[] s1=s.split(" "); for(String i:s1) System.out.println(i); } } Dr. Kuppusamy P
  • 18. String class - Methods & Example 20. toCharArray() method can split a String into n number of characters. public char[] toCharArray() Ex. public class StringEx2{ public static void main(String [] args) { String s="Welcome"; char[] c=s.toCharArray(); for(char i:c) System.out.println(i); } } Dr. Kuppusamy P
  • 19. String class - Methods & Example 21. contains() method used to check whether the given sub string is a part of the other string. public boolean contains(String s) Ex. public class StringEx3{ public static void main(String [] args) { String s="VIT-AP"; if(s.contains("VIT")) System.out.print("Welcome to VIT-AP"); } } Dr. Kuppusamy P
  • 20. String class - Methods & Example 22. format() method used to format any data into specified format of string. public static String format(String format, Object... args) Ex. String str1 = String.format("%d", 101); // Integer value String str2 = String.format("%s", "Amar Singh"); // String value String str3 = String.format("%f", 101.00); // Float value String str4 = String.format("%2.2f", 101.14325); // Float value with 2 points String str5 = String.format("%x", 10); // Hexadecimal value String str6 = String.format("%c", 'c’); // Char value Dr. Kuppusamy P
  • 21. StringBuffer Class and StringBuffer Class Predefined Methods Dr. Kuppusamy P
  • 22. StringBuffer class • String class is used to create a string of fixed length. • But StringBuffer class creates strings of flexible length which can be modified. • StringBuffer class objects are mutable, so they can be changeable • StringBuffer are declared as final. • StringBuffer class defines three constructors: 1. StringBuffer() • Creates empty object with initial capacity of 16 characters. 2. StringBuffer(int capacity) • Creates an empty (no character in it) object with a given capacity (not less than 0) for storing a string 3. StringBuffer(String str) • Create StringBuffer object with string object. • The initial capacity of the string buffer is 16, plus the length of the string arguments. • The value of str cannot be null, Dr. Kuppusamy P
  • 23. Create StringBuffer class StringBuffer sb1=new StringBuffer(); StringBuffer sb2=new StringBuffer(5); StringBuffer sb3=new StringBuffer("Welcome"); System.out.println(sb1.capacity()); // 16 System.out.println(sb1.length()); // 0 System.out.println(sb2.capacity()); // 10 System.out.println(sb2.length()); // 0 System.out.println(sb3.capacity()); // 23 System.out.println(sb3.length()); // 7 Dr. Kuppusamy P
  • 24. StringBuffer Class Methods 1. append() method - Append any data type with the string. public StringBuffer append(boolean b) Ex: StringBuffer sb3=new StringBuffer("Welcome"); sb3.append(" VIT-AP"); System.out.println(sb3); // Welcome VIT-AP 2. insert() - insert any data into string at any location. public StringBuffer insert(int offset, int i) Ex: StringBuffer sb3=new StringBuffer("Welcome VIT-AP"); sb3.insert(8, “to”); System.out.println(sb3); Dr. Kuppusamy P
  • 25. StringBuffer Class Methods 3. delete() method - deletes a sub string from the specified begin index to end index public StringBuffer delete(int start, int end) Ex: StringBuffer sb3=new StringBuffer("Welcome VIT-AP"); sb3.insert(8, “to”); System.out.println(sb3); // Welcome to VIT-AP sb3.delete(8, 16); System.out.println(sb3); // Welcome Dr. Kuppusamy P
  • 26. StringBuffer Class Methods 4. replace() –replaces part of this StringBuffer(substring) with another substring public StringBuffer replace(int start, int end, String str); Ex: StringBuffer sb3=new StringBuffer("Welcome"); sb3.replace(3, 7, "done"); System.out.println(sb3); // Weldone 5. reverse() –reverses the StringBuffer and store it in the same StringBuffer object. public StringBuffer replace(int start, int end, String str); Ex: StringBuffer sb3=new StringBuffer("Welcome"); sb3.reverse(); System.out.println(sb3); // emocleW Dr. Kuppusamy P
  • 27. StringBuffer Class Methods 6. tostring() – Represents the object of StringBuffer class into String StringBuffer sb3=new StringBuffer("Welcome"); sb3.reverse(); String s=sb3.toString(); System.out.println(s); Dr. Kuppusamy P
  • 28. References Dr. Kuppusamy P Herbert Schildt, “Java: The Complete Reference”, McGraw-Hill Education, Tenth edition, 2017.