0% found this document useful (0 votes)
26 views27 pages

Strings Class

Uploaded by

Tanmay Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views27 pages

Strings Class

Uploaded by

Tanmay Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

JAVA

What you learn ?

Java
 String  String Pool
 String methods  StringBuffer
 String VS StringBuffer Vs
 StringBuilder StringBuilder
 Regular Expression
String

o In Java, string is basically an object that represents sequence of char values.


An array of characters works same as Java string.

o The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

o The Java String is immutable which means it cannot be changed. Whenever we


change any string, a new instance is created. For mutable strings, you can use
StringBuffer and StringBuilder classes.
String in JAVA vs String in C++

In Java strings are immutable reference types.


In C++ strings are mutable and employ value semantics.

Two strings in C++ will evaluate true to a “==” operation if they contain the same
value, regardless of whether they are the same object or not.

In Java comparing two String variables with ‘==’ does a reference equality test.
Surprisingly you might declare the same two Strings and initialize them with the
same string literal — then you’d expect them not to have reference equality —
but they might still because of string interning.
String
There are two ways to create String object:
1.By string literal
2.By new keyword
1) String Literal

Java String literal is created by using double quotes.


Each time you create a string literal, the JVM checks
the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool.

For example:
String s1="Welcome";
String s2="Welcome";//
It doesn't create a new instance
String

2) By new keyword

String s=new String("Welcome"); //creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool. The
variable s will refer to the object in a heap (non-pool).
String Pool
String methods
Method Description Return Type
charAt() Returns the character at the specified index char
(position)
codePointAt() Returns the Unicode of the character at the int
specified index
codePointBefo Returns the Unicode of the character before the int
re() specified index
codePointCou Returns the number of Unicode values found in a int
nt() string.
compareTo() Compares two strings lexicographically int
compareToIgn Compares two strings lexicographically, ignoring int
oreCase() case differences
String methods
Method Description Return Type
concat() Appends a string to the end of another string String
contains() Checks whether a string contains a sequence of boolean
characters
contentEquals Checks whether a string contains the exact same boolean
() sequence of characters of the specified
CharSequence or StringBuffer
copyValueOf() Returns a String that represents the characters of String
the character array
endsWith() Checks whether a string ends with the specified boolean
character(s)
equals() Compares two strings. Returns true if the strings boolean
are equal, and false if not
String methods
Method Description Return Type
equalsIgnoreC Compares two strings, ignoring case considerations boolean
ase()
format() Returns a formatted string using the specified String
locale, format string, and arguments
getBytes() Encodes this String into a sequence of bytes using byte[]
the named charset, storing the result into a new
byte array
getChars() Copies characters from a string to an array of chars void
hashCode() Returns the hash code of a string int
indexOf() Returns the position of the first found occurrence int
of specified characters in a string
String methods
Method Description Return Type
intern() Returns the canonical representation for the String
string object
isEmpty() Checks whether a string is empty or not boolean
lastIndexOf() Returns the position of the last found int
occurrence of specified characters in a string
length() Returns the length of a specified string int
matches() Searches a string for a match against a regular boolean
expression, and returns the matches
offsetByCodePoints Returns the index within this String that is int
() offset from the given index by codePointOffset
code points
regionMatches() Tests if two string regions are equal boolean
String methods
Method Description Return Type
replace() Searches a string for a specified value, and returns a String
new string where the specified values are replaced

replaceFirst() Replaces the first occurrence of a substring that String


matches the given regular expression with the given
replacement
replaceAll() Replaces each substring of this string that matches String
the given regular expression with the given
replacement
split() Splits a string into an array of substrings String[]
startsWith() Checks whether a string starts with specified boolean
characters
substring() Returns a new string which is the substring of a String
specified string
String methods
Method Description Return Type
toCharArray() Converts this string to a new character array char[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends of a string String
valueOf() Returns the string representation of the String
specified value
substring() Returns a new string which is the substring of String
a specified string
subSequence() Returns a new character sequence that is a CharSequence
subsequence of this sequence
StringBuffer

StringBuffer is a peer class of String that provides much of the functionality of


strings. The string represents fixed-length, immutable character sequences
while StringBuffer represents growable and writable character sequences.

StringBuffer may have characters and substrings inserted in the middle or


appended to the end. It will automatically grow to make room for such
additions and often has more characters preallocated than are actually
needed, to allow room for growth.

StringBuffer class is used to create mutable (modifiable) string. The


StringBuffer class in java is same as String class except it is mutable i.e. it can
be changed.
StringBuffer
Important constructors of StringBuffer class:

Constructor Description
StringBuffer() It creates an empty String buffer with the
initial capacity of 16.

StringBuffer(String str) It creates a String buffer with the specified


string..

StringBuffer(int capacity) It creates an empty String buffer with the


specified capacity as length.
StringBuffer
Methods of StringBuffer class:
Methods Action Performed
append() Used to add text at the end of the existing text.

length() The length of a StringBuffer can be found by the length( ) method

capacity() the total allocated capacity can be found by the capacity( ) method

charAt() This method returns the char value in this sequence at the specified index.

delete() Deletes a sequence of characters from the invoking object

deleteCharAt() Deletes the character at the index specified by loc

ensureCapacity() Ensures capacity is at least equals to the given minimum.

insert() Inserts text at the specified index position

length() Returns length of the string

reverse() Reverse the characters within a StringBuffer object

replace() Replace one set of characters with another set inside a StringBuffer object
StringBuilder

StringBuilder in Java represents a mutable sequence of characters.

Since the String Class in Java creates an immutable sequence of characters, the
StringBuilder class provides an alternative to String Class, as it creates a
mutable sequence of characters.

The function of StringBuilder is very much similar to the StringBuffer class, as


both of them provide an alternative to String Class by making a mutable
sequence of characters.

However, the StringBuilder class differs from the StringBuffer class on the
basis of synchronization. The StringBuilder class provides no guarantee of
synchronization whereas the StringBuffer class does.
StringBuilder
Important constructors of StringBuilder class:

Constructor Description
StringBuilder() It creates an empty String Builder with the
initial capacity of 16.

StringBuilder(String str) It creates a String Builder with the


specified string.

StringBuilder(int length) It creates an empty String Builder with the


specified capacity as length.
StringBuilder
Methods of StringBuilder class:

Methods Action Performed

public StringBuilder It is used to append the specified string with this string. The append() method is
append(String s) overloaded like append(char), append(boolean), append(int), append(float),
append(double) etc.

public StringBuilder It is used to insert the specified string with this string at the specified position.
insert(int offset, String s) The insert() method is overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.

public StringBuilder
replace(int startIndex, int It is used to replace the string from specified startIndex and endIndex.
endIndex, String str)

public StringBuilder
delete(int startIndex, int It is used to delete the string from specified startIndex and endIndex.
endIndex)

public StringBuilder
reverse() It is used to reverse the string.
StringBuilder
Methods of StringBuilder class:

Methods Action Performed


public int capacity() It is used to return the current capacity.

public void
ensureCapacity(int It is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)

public char charAt(int


index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total number of characters.
public String substring(int
beginIndex) It is used to return the substring from the specified beginIndex.

public String substring(int


beginIndex, int endIndex) It is used to return the substring from the specified beginIndex and endIndex.
String VS StringBuffer VS StringBuilder
Regular Expression
 Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be
used for searching, manipulating, and editing a string in Java.

 Email validation and passwords are a few areas of strings where Regex is widely used to define
the constraints.

 Regular Expressions are provided under java.util.regex package.

 This consists of 3 classes and 1 interface.


S. No. Class/Interface Description

1. Pattern Class Used for defining patterns

2. Matcher Class Used for performing match operations on text using


patterns

3. PatternSyntaxException Class Used for indicating syntax error in a regular


expression pattern

4. MatchResult Interface Used for representing the result of a match operation


Regular Expression
Pattern Class:
This class is a compilation of regular expressions that can be used to define
various types of patterns, providing no public constructors.
This can be created by invoking the compile() method which accepts a regular
expression as the first argument, thus returns a pattern after execution.

Example:
/* Following line prints "true" because the whole text "geeksforgeeks" matches
pattern "geeksforge*ks"
*/

System.out.println(Pattern.matches("geeksforge*ks", "geeksforgeeks"));
Regular Expression
Matcher Class:
This object is used to perform match operations for an input string in java, thus
interpreting the previously explained patterns. This too defines no public constructors.
This can be implemented by invoking a matcher() on any pattern object.
Example:
// Create a pattern to be searched Custom pattern
Pattern pattern = Pattern.compile("geeks");

// Search above pattern in "geeksforgeeks.org"


Matcher m = pattern.matcher("geeksforgeeks.org");

// Finding string using find() method


while (m.find())

// Print starting and ending indexes of the pattern in the text


System.out.println("Pattern found from "+ m.start() + " to "+ (m.end() - 1));
Regular Expression
Patterns
The first parameter of the Pattern.compile() method is the pattern. It describes what
is being searched for.

Brackets are used to find a range of characters:

Expression Description
[abc] Find one character from the options between the
brackets
[^abc] Find one character NOT between the brackets
[0-9] Find one character from the range 0 to 9
Regular Expression
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit

\s Find a whitespace character


\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word
like this: WORD\b

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Regular Expression
Quantifiers
Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{x} Matches any string that contains a sequence of X n's
n{x,y} Matches any string that contains a sequence of X to Y n's

n{x,} Matches any string that contains a sequence of at least X n's


Thanks

Anirudha Gaikwad

You might also like