0% found this document useful (0 votes)
13 views

String and String Buffer

.....

Uploaded by

anshj9797
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

String and String Buffer

.....

Uploaded by

anshj9797
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

String Handling

• String is probably the most commonly used class in java library. String
class is encapsulated under java.lang package. In java, every string
that you create is actually an object of type String. One important
thing to notice about string object is that string objects are
immutable that means once a string object is created it cannot be
altered.
• What is an Immutable object?
• An object whose state cannot be changed after it is created is known
as an Immutable object. String, Integer, Byte, Short, Float, Double
and all other wrapper class's objects are immutable.
Creating a String object

• String can be created in number of ways, here are a few ways of


creating string object.
• 1) Using a String literal
• String literal is a simple string enclosed in double quotes " ". A string
literal is treated as a String object.
• String str1 = "Hello";
• 2) Using another String object
• String str2 = new String(str1);

• 3) Using new Keyword


• String str3 = new String("Java");

• 4) Using + operator (Concatenation)


• String str4 = str1 + str2;
• or,
• String str5 = "hello"+"Java";
Each time you create a String literal, the JVM checks the string pool
first. If the string literal already exists in the pool, a reference to the
pool instance is returned. If string does not exist in the pool, a new
string object is created, and is placed in the pool. String objects are
stored in a special memory area known as string constant pool inside
the heap memory.
Heap Memory
Heap memory is a part of memory allocated to JVM,
which is shared by all executing threads in the
application. It is the part of JVM in which all class
instances and are allocated. It is created on the Start-
up process of JVM. It does not need to be contiguous,
and its size can be static or dynamic. Space allocated
to the memory is reclaimed through an automatic
memory management process called garbage
collection. Heap memory is a shared area that is
utilized during the runtime of Java applications. It is
created during the instantiation of Java Virtual
Machine (JVM).
• Concatenating String
• There are 2 methods to concatenate two or more string.
• Using concat() method
• Using + operator
• 1) Using concat() method
• string s = "Hello";
• string str = "Java";
• string str2 = s.concat(str);
• String str1 = "Hello".concat("Java"); //works with string literals too.
• 2) Using + operator
• string str = "Rahul";
• string str1 = "Dravid";
• string str2 = str + str1;
• string st = "Rahul"+"Dravid";
• String Comparison
• String comparison can be done in 3 ways.
• Using equals() method
• Using == operator
• By CompareTo() method
• Using equals() method
• equals() method compares two strings for equality. Its general syntax is,
• boolean equals (Object str)
• It compares the content of the strings. It will return true if string
matches, else returns false.
• String s = "Hell";
• String s1 = "Hello";
• String s2 = "Hello";
• s1.equals(s2); //true
• s.equals(s1) ; //false
• Using == operator
• == operator compares two object references to check whether they
refer to same instance. This also, will return true on successful match.
• String s1 = "Java";
• String s2 = "Java";
• String s3 = new string ("Java");
• test(Sl == s2) //true
• test(s1 == s3) //false
• In Java, the main difference between the == operator
and the equals() method is that == compares the
references of objects, while equals() compares the
objects' contents:
• Type == is an operator, while equals() is a method.
• What it compares == compares the memory addresses
of objects, while equals() compares the objects'
contents.
• What it can be used with == can be used with both
objects and primitives, while equals() cannot be used
with primitives.
• By compareTo() method
• compareTo() method compares values and returns an int which tells if
the string compared is less than, equal to or greater than th other string.
Its general syntax is,
• int compareTo(String str)
• To use this function you must implement the Comparable Interface.
compareTo() is the only function in Comparable Interface.
• String s1 = "Abhi";
• String s2 = "Viraaj";
• String s3 = "Abhi";
• s1.compareTo(S2); //return -1 because s1 < s2
• s1.compareTo(S3); //return 0 because s1 == s3
• s2.compareTo(s1); //return 1 because s2 > s1
String class function

• The following methods are some of the most commonly used


methods of String class.
• charAt()
• charAt() function returns the character located at the specified index.
• String str = "studytonight";
• System.out.println(str.charAt(2));
• Output : u
• equalsIgnoreCase()
• equalsIgnoreCase() determines the equality of two Strings, ignoring
thier case (upper or lower case doesn't matters with this fuction ).
• String str = "java";
• System.out.println(str.equalsIgnoreCase("JAVA"));
• Output : true
• length()
• length() function returns the number of characters in a String.
• String str = "Count me";
• System.out.println(str.length());
• Output : 8
• replace()
• replace() method replaces occurances of character with a specified
new character.
• String str = "Change me";
• System.out.println(str.replace('m','M'));
• Output : Change Me
• substring()
• substring() method returns a part of the string. substring() method has
two forms,
• public String substring(int begin);

• public String substring(int begin, int end);
• The first argument represents the starting point of the subtring. If the
substring() method is called with only one argument, the subtring
returned, will contain characters from specified starting point to the end
of original string.
• But, if the call to substring() method has two arguments, the second
argument specify the end point of substring.
• String str = "0123456789";
• System.out.println(str.substring(4));
• Output : 456789
• System.out.println(str.substring(4,7));
• Output : 456
• toLowerCase()
• toLowerCase() method returns string with all uppercase characters
converted to lowercase.
• String str = "ABCDEF";
• System.out.println(str.toLowerCase());
• Output : abcdef
• valueOf()
• Overloaded version of valueOf() method is present in String class for
all primitive data types and for type Object.
• NOTE : valueOf() function is used to convert primitive data types into
Strings.
• But for objects, valueOf() method calls toString() function.
• toString()
• toString() method returns the string representation of the object
used to invoke this method. toString() is used to represent any Java
Object into a meaningful string representation. It is declared in
the Object class, hence can be overrided by any java class. (Object
class is super class of all java classes.)
• public class Car {
• public static void main(String args[])
• {
• Car c=new Car();
• System.out.println(c);
• }
• public String toString()
• {
• return "This is my car object";
• }
•}
• Output : This is my car object
• Whenever we will try to print any object of class Car, its toString()
function will be called. toString() can also be used with normal string
objects.
• String str = "Hello World";
• System.out.println(str.toString());
• Output : Hello World
• toString() with Concatenation
• Whenever we concatenate any other primitive data type, or object of
other classes with a String object,toString() function
or valueOf() function is called automatically to change the other object
or primitive type into string, for successful concatenation.
• int age = 10;
• String str = "He is" + age + "years old.";
• In above case 10 will be automatically converted into string for
concatenation using valueOf() function.
• toUpperCase()
• This method returns string with all lowercase character changed to
uppercase.
• String str = "abcdef";
• System.out.println(str.toLowerCase());
• Output : ABCDEF
• trim()
• This method returns a string from which any leading and trailing
whitespaces has been removed.
• String str = " hello ";
• System.out.println(str.trim());
• Output : hello
StringBuffer class
StringBuffer class is used to create a mutable string object. It represents
growable and writable character sequence. As we know that String
objects are immutable, so if we do a lot of changes with String objects,
we will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications
to our string. It is also thread safe i.e multiple threads cannot access it
simultaneously. StringBuffer defines 4 constructors. They are,
• StringBuffer ( )
• StringBuffer ( int size )
• StringBuffer ( String str )
• StringBuffer ( charSequence [ ]ch )
• StringBuffer() creates an empty string buffer and reserves room for
16 characters.
• stringBuffer(int size) creates an empty string and takes an integer
argument to set capacity of the buffer.
• Example showing difference between String and StringBuffer
• class Test {
• public static void main(String args[])
• {
• String str = "study";
• str.concat("tonight");
• System.out.println(str); // Output: study

• StringBuffer strB = new StringBuffer("study");
• strB.append("tonight");
• System.out.println(strB); // Output: studytonight
• }
•}
• Important methods of StringBuffer class
• The following methods are some most commonly used methods of
StringBuffer class.
• append()
• This method will concatenate the string representation of any type of
data to the end of the invokingStringBuffer object. append() method has
several overloaded forms.
• StringBuffer append(String str)

• StringBuffer append(int n)

• StringBuffer append(Object obj)
• The string representation of each parameter is appended
to StringBuffer object.
• StringBuffer str = new StringBuffer("test");
• str.append(123);
• System.out.println(str);
• Output : test123
• insert()
• This method inserts one string into another. Here are few forms of
insert() method.
• StringBuffer insert(int index, String str)

• StringBuffer insert(int index, int num)

• StringBuffer insert(int index, Object obj)
• Here the first parameter gives the index at which position the string will
be inserted and string representation of second parameter is inserted
into StringBuffer object.
• StringBuffer str = new StringBuffer("test");
• str.insert(4, 123);
• System.out.println(str);
• Output : test123
• reverse()
• This method reverses the characters within a StringBuffer object.
• StringBuffer str = new StringBuffer("Hello");
• str.reverse();
• System.out.println(str);
• Output : olleH
• replace()
• This method replaces the string from specified start index to the end
index.
• StringBuffer str = new StringBuffer("Hello World");
• str.replace( 6, 11, "java");
• System.out.println(str);
• Output : Hello java
• capacity()
• This method returns the current capacity of StringBuffer object.
• StringBuffer str = new StringBuffer();
• System.out.println( str.capacity() );
• Output : 16
• ensureCapacity()
• This method is used to ensure minimum capacity
of StringBuffer object.
• StringBuffer str = new StringBuffer("hello");
• str.ensureCapacity(10);
• The Search Methods in the String Class
• Method
• Description
• int indexOf(int ch)
int lastIndexOf(int ch)
• Returns the index of the first (last) occurrence of the specified character.
• int indexOf(int ch, int fromIndex)
int lastIndexOf(int ch, int fromIndex)
• Returns the index of the first (last) occurrence of the specified character,
searching forward (backward) from the specified index.
• int indexOf(String str)
int lastIndexOf(String str)
• Returns the index of the first (last) occurrence of the specified substring.
• int indexOf(String str, int fromIndex)
int lastIndexOf(String str, int fromIndex)
• Returns the index of the first (last) occurrence of the specified substring,
searching forward (backward) from the specified index.
• boolean contains(CharSequence s)
• Returns true if the string contains the specified character sequence.
• Methods in the String Class for Manipulating Strings
• Method
• Description
• String replace(char oldChar, char newChar)
• Returns a new string resulting from replacing all occurrences of oldChar
in this string with newChar.
• String replace(CharSequence target, CharSequence replacement)
• Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence.
• String replaceAll(String regex, String replacement)
• Replaces each substring of this string that matches the given regular
expression with the given replacement.
• String replaceFirst(String regex, String replacement)
• Replaces the first substring of this string that matches the given regular
expression with the given replacement.
String Constant Pool in Java
• // Program 1: Comparing two references to objects
• // created using literals.
• import java.util.*;
• class GFG {
• public static void main(String[] args) {
• String s1 = "abc";
• String s2 = "abc";
• if (s1 == s2)
• System.out.println("Yes");
• else
• System.out.println("No"); }}
• Output: Yes
• import java.util.*;
• class GFG {
• public static void main(String[] args) {
• String s1 = new String("abc");
• String s2 = new String("abc");
• if (s1 == s2)
• System.out.println("Yes");
• else
• System.out.println("No"); } }

• Output:
• No
Let us understand why we get different output with below explanation.
String is a sequence of characters. One of the most important
characteristics of a string in Java is that they are immutable. In other
words, once created, the internal state of a string remains the same
throughout the execution of the program. This immutability is achieved
through the use of a special string constant pool in the heap. In this
article, we will understand about the storage of the strings.
• A string constant pool is a separate place in the heap memory
where the values of all the strings which are defined in the
program are stored. When we declare a string, an object of
type String is created in the stack, while an instance with the
value of the string is created in the heap. On standard
assignment of a value to a string variable, the variable is
allocated stack, while the value is stored in the heap in the
string constant pool. For example, let’s assign some value to a
string str1. In java, a string is defined and the value is assigned
as:
• String str1 = "Hello";
• The following illustration explains the memory allocation for
the above declaration:
https://media.geeksforgeeks.org/wp-content/uploads/20200601211147/string_pool_11.png
• In the above scenario, a string object is created in the stack, and the
value “Hello” is created and stored in the heap. Since we have normally
assigned the value, it is stored in the constant pool area of the heap. A
pointer points towards the value stored in the heap from the object in
the stack.
• Now, let’s take the same example with multiple string variables having
the same value as follows:
• String str1 = "Hello";
• String str2 = "Hello";
• The following illustration explains the memory allocation for the above
declaration:
https://media.geeksforgeeks.org/wp-content/uploads/20200601211203/string_pool_2.png
• In this case, both the string objects get created in the stack, but another
instance of the value “Hello” is not created in the heap. Instead, the
previous instance of “Hello” is re-used. The string constant pool is a small
cache that resides within the heap. Java stores all the values inside the
string constant pool on direct allocation. This way, if a similar value needs to
be accessed again, a new string object created in the stack can reference it
directly with the help of a pointer. In other words, the string constant pool
exists mainly to reduce memory usage and improve the re-use of existing
instances in memory. When a string object is assigned a different value, the
new value will be registered in the string constant pool as a separate
instance. Lets understand this with the following example:
• String str1 = "Hello";
• String str2 = "Hello";
• String str3 = "Class";
• The following illustration explains the memory allocation for the above
declaration:
https://media.geeksforgeeks.org/wp-content/uploads/20200602014728/string_pool_3.png
One way to skip this memory allocation is to use
the new keyword while creating a new string object.
The ‘new’ keyword forces a new instance to always be
created regardless of whether the same value was
used previously or not. Using ‘new’ forces the
instance to be created in the heap outside the string
constant pool which is clear, since caching and re-
using of instances isn’t allowed here. Let’s understand
this with an example:
String str1 = new String("John");
String str2 = new String("Doe");
The following illustration explains the memory
allocation for the above declaration:
StringTokenizer class

• The stringTokenizer class splits text or string into tokens. A


token is a maximum sequence of consecutive characters that
are not delimiters (it can also be called a word).
• It splits the text into tokens/words by taking delimeters into
account. The tokenizer uses the default delimiter set" \t \n \r
\f': the space character, the tab character, the newline
character, the carriage-return character, and the form-feed
character. Delimiter characters themselves will not be treated
as tokens.
• StringTokenizer(String string_object/variable)

• StringTokenizer(String string_object/variable, String delimeters)


:
Important
The StringTokenizer method do not distinguish among identifiers,
numbers, and quoted strings, nor do they recognize and skip comments
and the set of delimiters (the characters that separate tokens or words)
may be specified either at the time of creation or on a per-token basis.
A StringTokenizer object internally maintains a current position within
the string to be tokenized. Some operations advance this current
position past the characters processed.
A token is returned by taking a substring of the string that was used to
create the StringTokeniz~r
object. The StringTokenizer is a utility which is available in the package
''java.uti!" and used as:
"import java. util.String'Iokenizer"
Example 1:
• StringTokenizer str = newStringTokenizer("Great India");
• System.out.println(str.nextToken( )); //extracts first token or word
• System.out.println(str.nextToken( )); //extracts second token or
word
• It prints the following output:
Great
India
• Note: The above example contains two words/tokens and print
statement is printing all the tokens of string. The above example can
also be written as given which gives the same output as above:
• String name= "Great India";
• StringTokenizer str = new StringTokenizer(nam);
• System.out.println(str.nextToken( )); Ilextracts first token or
word
• System.oui.println(str.nextToken( )); Ilextracts second token or
word
Commonly used functions/methods of StringTokenizer

S.No. Function Syntax Purpose


1. nextToken( ) string tokenizer , variable.nextToken( ) Returns the next token from
string initialized with string
tokenizer. In other words this
function extract consecutive
tokens from string.
2. hasMoreTokens( ) boolean hasMoreTokens() Checks and returns true if there
are more tokens available from
this tokenizer's string otherwise
returns false.
3. hasMoreElements( ) boolean hasMoreElements() Checks and returns true if there
are more tokens available from
this tokenizer's string otherwise
returns false. It is same as
hasMoreTokens( ).
4. countTokens( ) int countTokens( ) This function returns number
of tokens from the string by
using current set of delimeters.

You might also like