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 (20)

Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Java String
Java String Java String
Java String
 
Python strings
Python stringsPython strings
Python strings
 
Strings
StringsStrings
Strings
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
String Handling
String HandlingString Handling
String Handling
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Java variable types
Java variable typesJava variable types
Java variable types
 
Array and string
Array and stringArray and string
Array and string
 
Function in c
Function in cFunction in c
Function in c
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
OOP java
OOP javaOOP java
OOP java
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
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
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Strings in c
Strings in cStrings in c
Strings in c
 

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
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
Java string handling
Java string handlingJava string handling
Java string handling
 
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
 

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
 

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 arrays
Java arraysJava arrays
Java arrays
 
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
 

Recently uploaded

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

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.