SlideShare a Scribd company logo
1 of 67
String Handling
String Handling
• a string is a sequence of characters.
• Java implements strings as objects of type
String.
• once a String object has been created, you
cannot change the characters that comprise
that string
• You can still perform all types of string
operations.
• The difference is that each time you need an
altered version of an existing string, a new
String object is created that contains the
modifications.
• The original string is left unchanged.
• That we called string is immutable.
• StringBuffer, whose objects contain strings
that can be modified after they are created.
• Both the String and StringBuffer classes are
defined in java.lang.
The String Constructors
• Simple constructor:
String s = new String();
• To create a String initialized by an array of
characters
String(char chars[ ])
• An example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
• To specify a subrange of a character array as an
initializer :
String(char chars[ ], int startIndex, int numChars)
• startIndex specifies the index at which the
subrange begins,
• numChars specifies the number of characters to
use.
• an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
• construct a String object that contains the
same character sequence as another String
object
String(String strObj)
• strObj is a String object
Sample
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
• output
Java
Java
• Java’s char type uses 16 bits to represent the
Unicode character set,
• the String class provides constructors that
initialize a string when given a byte array.
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Sample
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
} }
• output:
ABCDEF
CDE
String Length
• The length of a string is the number of
characters that it contains.
• To obtain this value, call the length( ) method
int length( )
• Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Special String Operations
• concatenation of multiple String objects by
use of the + operator
String Literals
• String s2 = "abc"; // use string literal
• A String object is created for every string
literal, you can use a string literal any place
you can use a String object.
System.out.println("abc".length());
String Concatenation
• the + operator, which concatenates two
strings, producing a String object as the result.
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
• This displays the string “He is 9 years old.”
String Concatenation with Other Data
Types
• You can concatenate strings with other types
of data.
• example:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
• Example:
String s = "four: " + 2 + 2;
System.out.println(s);
• This fragment displays
four: 22
• rather than the
four: 4
• Example:
String s = "four: " + (2 + 2);
• Now s contains the string “four: 4”.
String Conversion and toString( )
• Java converts data into its string
representation during concatenation
• For the simple types, valueOf( ) returns a
string that contains the human-readable
equivalent of the value with which it is called.
• valueOf( ) calls the toString( ) method on the
object.
• you can override toString( ) and provide your
own string representations.
Sample
// Override toString() for Box class.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
public String toString() {
return "Dimensions are " + width + " by " +
depth + " by " + height + ".";
} }
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s);
}
}
• Output :
Dimensions are 10.0 by 14.0 by 12.0
Box b: Dimensions are 10.0 by 14.0 by 12.0
Character Extraction
• charAt( )
– To extract a single character from a String, you
can refer directly to an individual character.
char charAt(int where)
– Here, where is the index of the character that you
want to obtain.
– The value of where must be nonnegative and
specify a location within the string.
– charAt( ) returns the character at the specified
location.
– example,
char ch;
ch = "abc".charAt(1);
– assigns the value “b” to ch.
• getChars( )
– If you need to extract more than one character at
a time
void getChars(int sourceStart, int sourceEnd, char
target[ ], int targetStart)
– Here, sourceStart specifies the index of the
beginning of the substring,
– sourceEnd specifies an index that is one past the
end of the desired substring.
– The substring contains the characters from
sourceStart through sourceEnd–1.
– The array that will receive the characters is
specified by target.
– The index within target at which the substring will
– be copied is passed in targetStart.
Sample
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
} }
Output: demo
• getBytes( )
– There is an alternative to getChars( ) that stores
the characters in an array of bytes
byte[ ] getBytes( )
• toCharArray( )
– to convert all the characters in a String object into
a character array
– It returns an array of characters for the entire
string.
char[ ] toCharArray( )
String Comparison
• equals( )
boolean equals(Object str)
– Here, str is the String object being compared with
the invoking String object.
– It returns true if the strings contain the same
characters in the same order, and false otherwise.
– The comparison is case-sensitive.
• equalsIgnoreCase( )
– To perform a comparison that ignores case
differences, call equalsIgnoreCase( ).
– When it compares two strings, it considers A-Z to
be the same as a-z.
boolean equalsIgnoreCase(String str)
– Here, str is the String object being compared with
the invoking String object.
– It returns true if the strings contain the same
characters in the same order, and false otherwise.
Sample
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
} }
• Output :
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
• regionMatches( )
– compares a specific region inside a string with
another specific region in another string.
– There is an overloaded form that allows you to
ignore case in such comparisons.
boolean regionMatches(int startIndex, String
str2, int str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase,
int startIndex, String str2, int str2StartIndex, int
numChars)
and endsWith( )
• startsWith( )
– determines whether a given String begins with a
specified string.
boolean startsWith(String str)
• endsWith( )
– determines whether the String ends with a
specified string.
boolean endsWith(String str)
"Foobar".endsWith("bar")
"Foobar".startsWith("Foo")
– are both true.
– A second form of startsWith( ), lets you specify a
starting point:
boolean startsWith(String str, int startIndex)
– Here, startIndex specifies the index into the
invoking string at which point the search will
begin.
"Foobar".startsWith("bar", 3)
– returns true.
equals( ) Versus ==
• The == operator compares two object
references to see whether they refer to the
same instance.
• The equals( ) method compares the characters
inside a String object.
Sample
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
• Output:
Hello equals Hello -> true
Hello == Hello -> false
• compareTo( )
– to know which is less than, equal to, or greater
than
int compareTo(String str)
// A bubble sort for Strings.
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"
};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
} }
• Output :
Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
• compareToIgnoreCase( )
– to ignore case differences when comparing two
strings
int compareToIgnoreCase(String str)
“Now” will no longer be first.
Searching Strings
• indexOf( )
– Searches for the first occurrence of a character or
substring
int indexOf(int ch)
int indexOf(String str)
• lastIndexOf( )
– Searches for the last occurrence of a character or
substring.
int lastIndexOf(int ch)
int lastIndexOf(String str)
• You can specify a starting point for the search
using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
– Here, startIndex specifies the index at which point
– the search begins
– For lastIndexOf( ), the search runs from startIndex
to zero.
Modifying a String
• substring( )
– To extract a substring fro string
String substring(int startIndex)
– Here, startIndex specifies the index at which the
substring will begin.
– This form returns a copy of the substring that
begins at startIndex and runs to the end of the
invoking string.
– to specify both the beginning and ending index of
the substring
String substring(int startIndex, int endIndex)
– Here, startIndex specifies the beginning index, and
endIndex specifies the stopping point.
• concat( )
– To concatenate two strings
String concat(String str)
– This method creates a new object that contains
the invoking string with the contents of str
appended to the end.
String s1 = "one";
String s2 = s1.concat("two");
– puts the string “onetwo” into s2.
• replace( )
– To replaces all occurrences of one character in the
invoking string with another character.
String replace(char original, char replacement)
– Here, original specifies the character to be
replaced by replacement.
– The resulting string is returned
• trim( )
– To returns a copy of the invoking string from
which any leading and trailing whitespace has
been removed.
String trim( )
– example:
String s = " Hello World ".trim();
– This puts the string “Hello World” into s.
Data Conversion Using valueOf( )
• The valueOf( ) method converts data from its
internal format into a human-readable form.
• General form:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
Changing the Case of Characters
• toLowerCase( ) converts all the characters in a
string from uppercase to lowercase.
• toUpperCase( ) method converts all the
characters in a string from lowercase to
uppercase.
String toLowerCase( )
String toUpperCase( )
Sample
class ChangeCase {
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
} }
• Output :
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
StringBuffer
• StringBuffer is muttable.
• StringBuffer may have characters and
substrings inserted in the middle or appended
to the end.
StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
• The second version accepts an integer
argument that explicitly sets the size of the
buffer.
• The third version accepts a String argument
that sets the initial contents of the
StringBuffer object and reserves room for 16
more characters without reallocation.
length( ) and capacity( )
• The current length of a StringBuffer can be
found via the length( ) method.
• The total allocated capacity can be found
through the capacity( ) method.
• general form:
int length( )
int capacity( )
Sample
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
• output :
space for additional manipulations:
buffer = Hello
length = 5
capacity = 21
• ensureCapacity( )
– to preallocate room for a certain number of
characters after a StringBuffer has been
constructed, use ensureCapacity( ) to set the size
of the buffer.
void ensureCapacity(int capacity)
– Here, capacity specifies the size of the buffer.
• setLength( )
– To set the length of the buffer within a
StringBuffer object.
void setLength(int len)
– len specifies the length of the buffer.
– This value must be nonnegative.
– If you call setLength( ) with a value less than the
current value returned by length( ), then the
characters stored beyond the new length will be
lost.
• charAt( )
– The value of a single character can be obtained.
char charAt(int where)
– where specifies the index of the character being
obtained.
• setCharAt( )
– set the value of a character within a StringBuffer
void setCharAt(int where, char ch)
– where specifies the index of the character being
set, and ch specifies the new value of that
Sample
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
• Output :
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
• getChars( )
– To copy a substring of a StringBuffer into an array
– void getChars(int sourceStart, int sourceEnd, char
target[ ], int targetStart)
– sourceStart, sourceEnd specifies the index of the
beginning and end of the desired substring.
– The array that will receive the characters is
specified by target.
– The index within target at which the substring will
be copied is passed in targetStart
• append( )
– To concatenates the string representation of any
other type of data to the end of the invoking
StringBuffer object
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
– The buffer itself is returned by each version of
append( ).
Sample
– class appendDemo {
– public static void main(String args[]) {
– String s;
– int a = 42;
– StringBuffer sb = new StringBuffer(40);
– s = sb.append("a = ").append(a).append("!").toString();
– System.out.println(s);
– }
– }
• Output:
a = 42!
• insert( )
– To insert one string into another.
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
– index specifies the index at which point the string
will be inserted into the invoking StringBuffer
object
// Demonstrate insert().
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
• Output :
I like Java!
• reverse( )
– To reverse the characters within a StringBuffer
StringBuffer reverse( )
• Sample
– class ReverseDemo {public static void main(String args[]) {
– StringBuffer s = new StringBuffer("abcdef");
– System.out.println(s);
– s.reverse();
– System.out.println(s);
– } }
• Output :
abcdef
fedcba
• delete( )
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
– deletes a sequence of characters from the
invoking object.
– Here, startIndex specifies the index of the first
character to remove, and endIndex specifies an
index one past the last character to remove.
• deleteCharAt( )
StringBuffer deleteCharAt(int loc)
– deletes the character at the index specified by loc.
– It returns the resulting StringBuffer object.
Sample
• class deleteDemo {
• public static void main(String args[]) {
• StringBuffer sb = new StringBuffer("This is a test.");
• sb.delete(4, 7);
• System.out.println("After delete: " + sb);
• sb.deleteCharAt(0);
• System.out.println("After deleteCharAt: " + sb);
• }
• }
• The following output is produced:
After delete: This a test.
After deleteCharAt: his a test.
• replace( )
– It replaces one set of characters with another set
inside a StringBuffer object.
StringBuffer replace(int startIndex, int endIndex,
String str)
– The substring being replaced is specified by the
indexes startIndex and endIndex.
– Thus, the substring at startIndex through
endIndex–1 is replaced.
– The replacement string is passed in str.
Sample
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
• output:
After replace: This was a test
• substring( )
String substring(int startIndex)
String substring(int startIndex, int endIndex)
– first form returns the substring that starts at
startIndex and runs to the end of the invoking
StringBuffer object.
– second form returns the substring that starts at
startIndex and runs through endIndex–1.

More Related Content

What's hot

Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
Ravi_Kant_Sahu
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
myrajendra
 

What's hot (20)

Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java strings
Java   stringsJava   strings
Java strings
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Interface in java
Interface in javaInterface in java
Interface in java
 

Similar to Java string handling

Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
adityaraj7711
 

Similar to Java string handling (20)

L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
07slide
07slide07slide
07slide
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
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
 
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
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
Text processing
Text processingText processing
Text processing
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
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
 
StringBuffer.pptx
StringBuffer.pptxStringBuffer.pptx
StringBuffer.pptx
 

More from GaneshKumarKanthiah (11)

Software testing regression testing
Software testing  regression testingSoftware testing  regression testing
Software testing regression testing
 
Software testing acceptance testing
Software testing  acceptance testingSoftware testing  acceptance testing
Software testing acceptance testing
 
Software testing performance testing
Software testing  performance testingSoftware testing  performance testing
Software testing performance testing
 
Software testing introduction
Software testing  introductionSoftware testing  introduction
Software testing introduction
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java packages
Java packagesJava packages
Java packages
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java interface
Java interfaceJava interface
Java interface
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java awt
Java awtJava awt
Java awt
 
Java applet
Java appletJava applet
Java applet
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

Java string handling

  • 2. String Handling • a string is a sequence of characters. • Java implements strings as objects of type String. • once a String object has been created, you cannot change the characters that comprise that string • You can still perform all types of string operations.
  • 3. • The difference is that each time you need an altered version of an existing string, a new String object is created that contains the modifications. • The original string is left unchanged. • That we called string is immutable.
  • 4. • StringBuffer, whose objects contain strings that can be modified after they are created. • Both the String and StringBuffer classes are defined in java.lang.
  • 5. The String Constructors • Simple constructor: String s = new String(); • To create a String initialized by an array of characters String(char chars[ ]) • An example: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars);
  • 6. • To specify a subrange of a character array as an initializer : String(char chars[ ], int startIndex, int numChars) • startIndex specifies the index at which the subrange begins, • numChars specifies the number of characters to use. • an example: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3);
  • 7. • construct a String object that contains the same character sequence as another String object String(String strObj) • strObj is a String object
  • 8. Sample class MakeString { public static void main(String args[]) { char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); } } • output Java Java
  • 9. • Java’s char type uses 16 bits to represent the Unicode character set, • the String class provides constructors that initialize a string when given a byte array. String(byte asciiChars[ ]) String(byte asciiChars[ ], int startIndex, int numChars)
  • 10. Sample // Construct string from subset of char array. class SubStringCons { public static void main(String args[]) { byte ascii[] = {65, 66, 67, 68, 69, 70 }; String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii, 2, 3); System.out.println(s2); } } • output: ABCDEF CDE
  • 11. String Length • The length of a string is the number of characters that it contains. • To obtain this value, call the length( ) method int length( ) • Example: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length());
  • 12. Special String Operations • concatenation of multiple String objects by use of the + operator
  • 13. String Literals • String s2 = "abc"; // use string literal • A String object is created for every string literal, you can use a string literal any place you can use a String object. System.out.println("abc".length());
  • 14. String Concatenation • the + operator, which concatenates two strings, producing a String object as the result. String age = "9"; String s = "He is " + age + " years old."; System.out.println(s); • This displays the string “He is 9 years old.”
  • 15. String Concatenation with Other Data Types • You can concatenate strings with other types of data. • example: int age = 9; String s = "He is " + age + " years old."; System.out.println(s);
  • 16. • Example: String s = "four: " + 2 + 2; System.out.println(s); • This fragment displays four: 22 • rather than the four: 4
  • 17. • Example: String s = "four: " + (2 + 2); • Now s contains the string “four: 4”.
  • 18. String Conversion and toString( ) • Java converts data into its string representation during concatenation • For the simple types, valueOf( ) returns a string that contains the human-readable equivalent of the value with which it is called. • valueOf( ) calls the toString( ) method on the object. • you can override toString( ) and provide your own string representations.
  • 19. Sample // Override toString() for Box class. class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } public String toString() { return "Dimensions are " + width + " by " + depth + " by " + height + "."; } }
  • 20. class toStringDemo { public static void main(String args[]) { Box b = new Box(10, 12, 14); String s = "Box b: " + b; // concatenate Box object System.out.println(b); // convert Box to string System.out.println(s); } } • Output : Dimensions are 10.0 by 14.0 by 12.0 Box b: Dimensions are 10.0 by 14.0 by 12.0
  • 21. Character Extraction • charAt( ) – To extract a single character from a String, you can refer directly to an individual character. char charAt(int where) – Here, where is the index of the character that you want to obtain. – The value of where must be nonnegative and specify a location within the string. – charAt( ) returns the character at the specified location.
  • 22. – example, char ch; ch = "abc".charAt(1); – assigns the value “b” to ch. • getChars( ) – If you need to extract more than one character at a time void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
  • 23. – Here, sourceStart specifies the index of the beginning of the substring, – sourceEnd specifies an index that is one past the end of the desired substring. – The substring contains the characters from sourceStart through sourceEnd–1. – The array that will receive the characters is specified by target. – The index within target at which the substring will – be copied is passed in targetStart.
  • 24. Sample class getCharsDemo { public static void main(String args[]) { String s = "This is a demo of the getChars method."; int start = 10; int end = 14; char buf[] = new char[end - start]; s.getChars(start, end, buf, 0); System.out.println(buf); } } Output: demo
  • 25. • getBytes( ) – There is an alternative to getChars( ) that stores the characters in an array of bytes byte[ ] getBytes( ) • toCharArray( ) – to convert all the characters in a String object into a character array – It returns an array of characters for the entire string. char[ ] toCharArray( )
  • 26. String Comparison • equals( ) boolean equals(Object str) – Here, str is the String object being compared with the invoking String object. – It returns true if the strings contain the same characters in the same order, and false otherwise. – The comparison is case-sensitive.
  • 27. • equalsIgnoreCase( ) – To perform a comparison that ignores case differences, call equalsIgnoreCase( ). – When it compares two strings, it considers A-Z to be the same as a-z. boolean equalsIgnoreCase(String str) – Here, str is the String object being compared with the invoking String object. – It returns true if the strings contain the same characters in the same order, and false otherwise.
  • 28. Sample // Demonstrate equals() and equalsIgnoreCase(). class equalsDemo { public static void main(String args[]) { String s1 = "Hello"; String s2 = "Hello"; String s3 = "Good-bye"; String s4 = "HELLO"; System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3)); System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4)); System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4)); } }
  • 29. • Output : Hello equals Hello -> true Hello equals Good-bye -> false Hello equals HELLO -> false Hello equalsIgnoreCase HELLO -> true
  • 30. • regionMatches( ) – compares a specific region inside a string with another specific region in another string. – There is an overloaded form that allows you to ignore case in such comparisons. boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars) boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)
  • 31. and endsWith( ) • startsWith( ) – determines whether a given String begins with a specified string. boolean startsWith(String str) • endsWith( ) – determines whether the String ends with a specified string. boolean endsWith(String str)
  • 32. "Foobar".endsWith("bar") "Foobar".startsWith("Foo") – are both true. – A second form of startsWith( ), lets you specify a starting point: boolean startsWith(String str, int startIndex) – Here, startIndex specifies the index into the invoking string at which point the search will begin. "Foobar".startsWith("bar", 3) – returns true.
  • 33. equals( ) Versus == • The == operator compares two object references to see whether they refer to the same instance. • The equals( ) method compares the characters inside a String object.
  • 34. Sample class EqualsNotEqualTo { public static void main(String args[]) { String s1 = "Hello"; String s2 = new String(s1); System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); } } • Output: Hello equals Hello -> true Hello == Hello -> false
  • 35. • compareTo( ) – to know which is less than, equal to, or greater than int compareTo(String str)
  • 36. // A bubble sort for Strings. class SortString { static String arr[] = { "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "their", "country" }; public static void main(String args[]) { for(int j = 0; j < arr.length; j++) { for(int i = j + 1; i < arr.length; i++) { if(arr[i].compareTo(arr[j]) < 0) { String t = arr[j]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[j]); } } }
  • 38. • compareToIgnoreCase( ) – to ignore case differences when comparing two strings int compareToIgnoreCase(String str) “Now” will no longer be first.
  • 39. Searching Strings • indexOf( ) – Searches for the first occurrence of a character or substring int indexOf(int ch) int indexOf(String str) • lastIndexOf( ) – Searches for the last occurrence of a character or substring. int lastIndexOf(int ch) int lastIndexOf(String str)
  • 40. • You can specify a starting point for the search using these forms: int indexOf(int ch, int startIndex) int lastIndexOf(int ch, int startIndex) int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex) – Here, startIndex specifies the index at which point – the search begins – For lastIndexOf( ), the search runs from startIndex to zero.
  • 41. Modifying a String • substring( ) – To extract a substring fro string String substring(int startIndex) – Here, startIndex specifies the index at which the substring will begin. – This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string.
  • 42. – to specify both the beginning and ending index of the substring String substring(int startIndex, int endIndex) – Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. • concat( ) – To concatenate two strings String concat(String str) – This method creates a new object that contains the invoking string with the contents of str appended to the end.
  • 43. String s1 = "one"; String s2 = s1.concat("two"); – puts the string “onetwo” into s2. • replace( ) – To replaces all occurrences of one character in the invoking string with another character. String replace(char original, char replacement) – Here, original specifies the character to be replaced by replacement. – The resulting string is returned
  • 44. • trim( ) – To returns a copy of the invoking string from which any leading and trailing whitespace has been removed. String trim( ) – example: String s = " Hello World ".trim(); – This puts the string “Hello World” into s.
  • 45. Data Conversion Using valueOf( ) • The valueOf( ) method converts data from its internal format into a human-readable form. • General form: static String valueOf(double num) static String valueOf(long num) static String valueOf(Object ob) static String valueOf(char chars[ ])
  • 46. Changing the Case of Characters • toLowerCase( ) converts all the characters in a string from uppercase to lowercase. • toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. String toLowerCase( ) String toUpperCase( )
  • 47. Sample class ChangeCase { public static void main(String args[]) { String s = "This is a test."; System.out.println("Original: " + s); String upper = s.toUpperCase(); String lower = s.toLowerCase(); System.out.println("Uppercase: " + upper); System.out.println("Lowercase: " + lower); } } • Output : Original: This is a test. Uppercase: THIS IS A TEST. Lowercase: this is a test.
  • 48. StringBuffer • StringBuffer is muttable. • StringBuffer may have characters and substrings inserted in the middle or appended to the end.
  • 49. StringBuffer Constructors StringBuffer( ) StringBuffer(int size) StringBuffer(String str) • The second version accepts an integer argument that explicitly sets the size of the buffer. • The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.
  • 50. length( ) and capacity( ) • The current length of a StringBuffer can be found via the length( ) method. • The total allocated capacity can be found through the capacity( ) method. • general form: int length( ) int capacity( )
  • 51. Sample class StringBufferDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer = " + sb); System.out.println("length = " + sb.length()); System.out.println("capacity = " + sb.capacity()); } } • output : space for additional manipulations: buffer = Hello length = 5 capacity = 21
  • 52. • ensureCapacity( ) – to preallocate room for a certain number of characters after a StringBuffer has been constructed, use ensureCapacity( ) to set the size of the buffer. void ensureCapacity(int capacity) – Here, capacity specifies the size of the buffer.
  • 53. • setLength( ) – To set the length of the buffer within a StringBuffer object. void setLength(int len) – len specifies the length of the buffer. – This value must be nonnegative. – If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost.
  • 54. • charAt( ) – The value of a single character can be obtained. char charAt(int where) – where specifies the index of the character being obtained. • setCharAt( ) – set the value of a character within a StringBuffer void setCharAt(int where, char ch) – where specifies the index of the character being set, and ch specifies the new value of that
  • 55. Sample class setCharAtDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer before = " + sb); System.out.println("charAt(1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i'); sb.setLength(2); System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1)); } } • Output : buffer before = Hello charAt(1) before = e buffer after = Hi charAt(1) after = i
  • 56. • getChars( ) – To copy a substring of a StringBuffer into an array – void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) – sourceStart, sourceEnd specifies the index of the beginning and end of the desired substring. – The array that will receive the characters is specified by target. – The index within target at which the substring will be copied is passed in targetStart
  • 57. • append( ) – To concatenates the string representation of any other type of data to the end of the invoking StringBuffer object StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) – The buffer itself is returned by each version of append( ).
  • 58. Sample – class appendDemo { – public static void main(String args[]) { – String s; – int a = 42; – StringBuffer sb = new StringBuffer(40); – s = sb.append("a = ").append(a).append("!").toString(); – System.out.println(s); – } – } • Output: a = 42!
  • 59. • insert( ) – To insert one string into another. StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj) – index specifies the index at which point the string will be inserted into the invoking StringBuffer object
  • 60. // Demonstrate insert(). class insertDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } } • Output : I like Java!
  • 61. • reverse( ) – To reverse the characters within a StringBuffer StringBuffer reverse( ) • Sample – class ReverseDemo {public static void main(String args[]) { – StringBuffer s = new StringBuffer("abcdef"); – System.out.println(s); – s.reverse(); – System.out.println(s); – } } • Output : abcdef fedcba
  • 62. • delete( ) StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc) – deletes a sequence of characters from the invoking object. – Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove.
  • 63. • deleteCharAt( ) StringBuffer deleteCharAt(int loc) – deletes the character at the index specified by loc. – It returns the resulting StringBuffer object.
  • 64. Sample • class deleteDemo { • public static void main(String args[]) { • StringBuffer sb = new StringBuffer("This is a test."); • sb.delete(4, 7); • System.out.println("After delete: " + sb); • sb.deleteCharAt(0); • System.out.println("After deleteCharAt: " + sb); • } • } • The following output is produced: After delete: This a test. After deleteCharAt: his a test.
  • 65. • replace( ) – It replaces one set of characters with another set inside a StringBuffer object. StringBuffer replace(int startIndex, int endIndex, String str) – The substring being replaced is specified by the indexes startIndex and endIndex. – Thus, the substring at startIndex through endIndex–1 is replaced. – The replacement string is passed in str.
  • 66. Sample class replaceDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); System.out.println("After replace: " + sb); } } • output: After replace: This was a test
  • 67. • substring( ) String substring(int startIndex) String substring(int startIndex, int endIndex) – first form returns the substring that starts at startIndex and runs to the end of the invoking StringBuffer object. – second form returns the substring that starts at startIndex and runs through endIndex–1.