String objects in Java are immutable and stored in a string pool to improve performance. The StringBuffer class can be used to create mutable strings that can be modified after creation. It provides methods like append(), insert(), replace(), and delete() to modify the string content. The ensureCapacity() method on StringBuffer is used to reserve enough memory to reduce reallocation as the string is modified.
2. 1. Unlike C and C++, String in Java doesn't terminate with null character. Instead
String are Object in Java and backed by character array. You can get the character
array used to represent String in Java by calling toCharArray() method
of java.lang.String class of JDK.
2. Strings are immutable in Java it means once created you cannot modify content of
String. If you modify it by using toLowerCase(), toUpperCase() or any other
method, It always result in new String. Since String is final there is no way anyone
can extend String or override any of String functionality.
3. String is special class in Java and all String literal e.g. "abc" (anything which is
inside double quotes are String literal in Java) are maintained in a separate String
pool, special memory location inside Java memory. Any time you create a new
String object using String literal, JVM first checks String pool and if an object with
similar content available, than it returns that and doesn't create a new object. JVM
doesn't perform String pool check if you create object using new operator.
What is so SPECIAL about Strings in JAVA?
3. Char array vs String Declaration
String is an array of characters, represented as:
//String is an array of characters
char[] arrSample = {'R', 'O', 'S', 'E’};
String strSample_1 = new String (arrSample);
In technical terms, the String is defined as follows in the above example-
= new (argument);
Now we always cannot write our strings as arrays; hence we can define the String in Java
//Representation of String
String strSample_2 = "ROSE";
In JAVA strings are class objects and
implemented using two classes:-
String
StringBuffer.
4. Immutability
1. In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable. Once string object is created its data or
state can't be changed but a new string object is created.
eg: Suppose there are 5 reference variables, all refers to one
object "sachin".If one reference variable changes the value of the object,
it will be affected to all the reference variables. That is why string
objects are immutable in java.
2. Once string object is created its data or state can't be changed but a
new string object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutabl
e objects
}
} Here Sachin is not changed but a new object is created with
sachintendulkar. That is why string is known as immutable.
5. Disadvantages of Immutability
Less efficient — you need to create a new string and throw away the old one even for
small changes.
Example: class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
6. • There are two ways to create String object:
1) By string literal. 2)By new keyword.
1) By string literal: no new object will be created.
For Example: String s1=“welcome";
String s2=“welcome”;
7. 2) By new keyword:- create two objects and one reference variable
For Example: String s=new String(“Sachin");
String s=new String(“SachinTendulkar");//.
8. Does Java create 2 String objects internally?
Without “new” operator for String creation:
– Java looks into a String pool (collection of String objects).
– Try to find objects with same string value.
– If object exists new variable points to existing object.
– If object does not exist new object is created.
Efficiency reasons – to limit object creation
String greeting1 = “Hello Utah!”
String greeting2 = “Hello Utah!”
9. Concept of String pooling
greeting2
“Hello Utah!”
greeting1
Local Variable Table Pool of String Objects
w/o new operator both the objects point to same variable in string pool.
12. String Methods
Method Description
char charAt(int index) returns char value for the particular
index
int length() returns string length
static String format(String format, Object... args) returns a formatted string.
String substring(int beginIndex) returns substring for given begin
index.
String substring(int beginIndex, int endIndex) returns substring for given begin
index and end index.
boolean contains(CharSequence s) returns true or false after matching
the sequence of char value.
boolean isEmpty() checks if string is empty.
String concat(String str) concatenates the specified string.
String replace(char old, char new) replaces all occurrences of the
specified char value.
String replace(CharSequence old, CharSequence new) replaces all occurrences of the
specified CharSequence.
13. static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
String[] split(String regex) returns a split string matching regex.
String[] split(String regex, int limit) returns a split string matching regex and limit.
int indexOf(int ch) returns the specified char value index.
int indexOf(int ch, int fromIndex) returns the specified char value index starting
with given index.
int indexOf(String substring) returns the specified substring index.
int indexOf(String substring, int fromIndex) returns the specified substring index starting with
given index.
String toLowerCase() returns a string in lowercase.
String toLowerCase(Locale l) returns a string in lowercase using specified
locale.
String toUpperCase() returns a string in uppercase.
String trim() removes beginning and ending spaces of this
string.
static String valueOf(int value) converts given type into string. It is an overloaded
method.
14. String word1 = “re”;
String word2 = “think”;
String word3 = “ing”;
How to combine and make “rethinking” ?
Method 1: Plus “+” operator
String str = word1 + word2;
concatenates word1 and word2 “rethink”
Method 2: Use String’s “concat” method
String str = word1.concat (word2);
Now str has value “rethink”, how to make “rethinking”?
String word3 = “ing”;
Method 3: Shorthand
str += word3; //results in “rethinking” (same as method1)
What if we wanted to combine String values?
15. CompareString
String s1 = "ABCD”;
String s2 = "ABCD”;
if(s1 == s2)
System.out.println("Equal");
else
System.out.println("NOT Equal");
In Java, when the“==” operator is used to
compare2 objects, it checks to see if the
objects refer to the same place in memory.
To check if strings have same data, use equals
String s1 = new String("ABCD");
String s2 = new String("ABCD");
if(s1.equals(s2))
System.out.println("Equal");
else
System.out.println("NOT Equal");
16. What is mutable string?
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
STRINGBUFFER class creates strings flexible length that can be modified in terms of both length
and content.
STRINGBUFFER may have characters and substrings inserted in the middle or appended to the
end.
STRINGBUFFER automatically grows to make room for such additions.
StringBuffer
17. String Buffer():- Reserves room for 16 characters without reallocation
StringBuffer(int size):- Accepts an integer argunent that explicilty sets the size of
the buffer
StringBuffer(String str):- Accepts STRING argument that sets the initial contents
of the STRINGBUFFER and allocated room for 16 additional characters.
STRINGBUFFER
CONSTRUCTORS
18. Example - Methods
public class StringBuff {
public static void main(String args[]) {
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
sb.delete(1,3);
System.out.println(sb);//prints Hlo
sb.reverse();
System.out.println(sb);//prints olleH
sb.append("java is my favourite language");
System.out.println(sb.capacity());
sb.ensureCapacity(10);
System.out.println(sb.capacity());
sb.ensureCapacity(50);
System.out.println(sb.capacity());
}
}
19. Modifier and Type Method Description
public synchronized StringBuffer append(String s) is used to append the specified string
with this string. The append() method
is overloaded like append(char),
append(boolean), append(int),
append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String s) is used to insert the specified string
with this string at the specified
position. The insert() method is
overloaded like insert(int, char),
insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public synchronized StringBuffer replace(int startIndex, int endIndex, String str) is used to replace the string from
specified startIndex and endIndex.
public synchronized StringBuffer delete(int startIndex, int endIndex) is used to delete the string from
specified startIndex and endIndex.
public synchronized StringBuffer reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least
equal to the given minimum.
public char charAt(int index) is used to return the character at the
specified position.
public int length() is used to return the length of the
string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the
specified beginIndex.
public String substring(int beginIndex, int endIndex) is used to return the substring from the
specified beginIndex and endIndex.
String Buffer Methods
20. Discussion Questions
Question 1: What is the use of ensureCapacity()?
Question 2: Explain the scenarios to choose between String and StringBuffer ?
Question 3: In how many ways you can create string objects in java?
21. Choose the correct Option
Q 1. If two strings are same, then method public int compareTo returns:
a)Null
b) Positive
c) Negative
d) Zero
Q 2. All operands are appended by calling toString method, if needed:
a) True
b) False
c) None of these