String class
June 7, 2025 6:17 PM
1. String is a predefined class, it is in [Link] package.
2. String is a final class, that can't be extended further [methods cannot be override further]
3. String is a sequence of characters i.e. String str = "techno", str is build using 6 characters.
4. String is an immutable object which means it is constant and cannot be changed at the same memory location once it has been
created.
5. How many times the memory has been initialized?
String str1 = "Hi";
str1 = "Hello";
Ans --> 2 times
6. Few examples:
Public static void main(String [] args){
String str1 = "Hi";
String str2 = new String("Hi");
String str3 = str2;
String str4 ="Hi";
String str5 = new String("Hi");
String str6 = "HI";
}
Let's understand it in detail:
How many time the memory gets initialized?
String str1 = "Hi" // SCP
String str2 = new String("Hi"); // Heap memory, new object is created
String str3 = str2; // str3 will start pointing to where str2 is pointing
String str4 ="Hi"; //exists in SCP, will point there
String str5 = new String("Hi"); // Heap memory, new object is created
String str6 = "HI"; // creates a new memory in SCP
------------------------------
Few Examples :
String str1 = "Hi";
String str2 = new String("Hi");
sop(str1 == str2); ///false
String str1 = "hi";
String str2 = "HI";
String str3 = [Link]();
sop(str1 == str3); // true false
--> String can be created in two ways.
1) String str = "Techno";
2) String str = new String("Techno");
-------------------------------------------
String str1 = new String("Hi");
String str2 = new String("Hi");
str1 = str2;
Java- April 2025 Page 1
str1 = str2;
Sop(str1 == str2); // true
---------------------------------------
String class methods :
1) char charAt(int index)
Returns the character at the provided index
Max Index : [Link]()-1
Min Index : 0
2) boolean equals(String str)
Compares the two strings contents , returns 'true' if matches else false
ie. [Link](str2)
"Hi".equals(str2);
String stdName = "";
String stdName = null; // default value is null
if([Link]() >0){ // NullPointer Expection
sop(stdName);
}
[Link] isEmpty()
Checks if the string is empty or not. Here, "" is being checked and not 'null'
String str = ""; // empty string, non- initialized
String str = null; // initialized with null value,
Imp Note: Here there is a probability of NullPointerException[NPE] when any string class method is called on str before
initializing it.
String str = "Kangan";
str = "";
if([Link]()){
4. boolean equalIgnoreCase(String str)
Compares the contents of the first string with the second that is provided as a parameter by ignoring the case.
Returns true if the content matches else false
String str1 = "Hi";
String str2 = "hi";
if([Link](str2))
5. boolean startsWith(String prefix)
Checks if the string that starts with the provided prefix. If it matches then performs further required operations on it.
String url = "[Link]
if([Link]("http") || [Link]("https"))
6. boolean endsWith(String suffix)
Checks if the string that ends with the provided suffix. If it matches then performs further required operations on it.
String str = "Techno_12345";
If([Link]("12345"){
// perform some operation here.
}
7. int indexOf(char ch)
Java- April 2025 Page 2
7. int indexOf(char ch)
Returns the first index of the provided character
String str = "technocredits";
for(int index=0;index<[Link]();index++){
char ch = [Link](index);
if([Link](ch) == [Link](ch))
sop(ch);
}
8. int lastIndexOf(char ch)
Returns the last index of the provided character
String str = "technocredits";
int index = [Link]('e'); // returns 8
Also, refer the above example, where it is comparing the first and the last index and if it is same then it is printing the c haracter
i.e. single occurrence of the character is being checked.
9. String subString(int startIndex)
It will return substring from startIndex to end of the String
Note:
It is an overloaded method of String class
10. Sttring subString(int startIndex, int endIndex)
It will return substring from startIndex (included) till endIndex(excluded)
Example:
String str = "technocredits";
str = [Link](3,5); // hn
11. String toUpperCase()
Converts the string to upper case
Example:
String str = "technocredits";
String upperSting = [Link]();
Sop(upperString); // TECHNOCREDITS
12. String toLowerCase()
Converts the string to lower case
Example:
String name = "Technocredits";
[Link]();
[Link](3);
[Link]();
[Link]([Link](0)); // T
13. int length()
Returns the length of the input string.
Example:
String name = "Technocredits";
Sop([Link]()); // 13
14. boolean contains(String s)
Returns true if the input string contains the provided string else false
Example:
String str = "Hi hello techno credits technocredits";
Java- April 2025 Page 3
String str = "Hi hello techno credits technocredits";
[Link]("c");// true
[Link]("hello");//false
[Link]("its"); //true
Imp:
Interview Q : String str = "hi techno hello techno hey techno Aashvi";
How many times techno word is repeating in given string.
// TODO : Access Modifier will be given as per business requirement.
int getWordCount(String str){
int count = 0;
String[] arr = [Link](" ");
for(int index=0;index<[Link];index++){
if(arr[index].equals("techno"))
count++;
}
sop(count);
return count;
}
15. String replace()
It is an overloaded method of string class which accepts target and replacement as both char and string
Example1:
Example 2: [Overloaded method - also accepts string]
16. int compareTo(String str)
String firstString = "Aashviz"; // 122 - 97 [25]
String secondString = "Aashvi";
[Link](secondString);
if compareTo method returns 0, both Strings are identical.
if it returns +ve, first string is bigger than Second one.
if it returns -ve, first string < second string.
Examaple:
Java- April 2025 Page 4
17. String intern()
This method brings the object from the heap memory to the String Constant Pool [SCP] to compare it further.
String intern(object) --> transfers it to SCP and hence if similar content is present in SCP then the == and .equals will same
18. String replaceFirst(String oldString, String newStr)
Replaces the first occurrence only
Example:
19. String replaceAll(String regx, string replacement)
Replaces all the occurrences of the provided regular expression
Example:
20. String[] spilt(String regx)
Used to break the string into individual words. Split returns a string array and will store it in a String array
Example 1:
String str = " The rains have started here";
String temp[] = [Link](" ");
String temp[] = [Link]("have");
This will give you 2 strings which has the
part1= The rains and
part2= started here
Example 2:
String str = "Hi hello techno hello gm";
String[] arr = [Link](" ");
sop([Link]); //5
Java- April 2025 Page 5
sop([Link]); //5
21. String valueOf(int i) : overloaded method
Returns the string representation of the provided integer.
[Link]([Link](10)); //10
22. contentEquals(StringBuffer sb)
Compares the character sequence with the input string and if it matches then returns true else false.
Imp: can be used to compare String content with StringBuffer content
Example :
23. char[] toCharArray()
Converts the provided string to a character array
Example:
StringBuffer and StringBuilder:
Example: Palindrome
public static void main(String[] args) {
String str1 = "tnaman";
StringBuffer sb1 = new StringBuffer(str1);
StringBuffer sb2 = new StringBuffer(str1);
[Link]();
if ([Link](sb2)) // compare memory address not content. to compare content we have to compare it on String.
[Link]().equals([Link]())
[Link]("palindrome");
else
[Link]("not");
}
Java- April 2025 Page 6
}
-----------------------------------------------
Reason : equals [what exactly it compares in case of StringBuffer] :
Ans [equals method is not overridden in StringBuffer class, object class equals method compares references. Hence equals
method return false while comparing 2 objects of StringBuffer class]
Important Questions:
Que: What is the difference between -
String str1 = "Techno";
String str2 = new String("Techno");
Ans : String str1 = "Techno"; // gets created in SCP[String constant pool]
String str2 = new String("Techno"); // gets created in Heap memory
String str1 = "Techno"; --> in this case, it first checks if the same string is present in CSP then point to the same else it will create
a new one.
It is case sensitive.
Advantage:
It helps in optimizing the memory and in turn increases the [Link] str2 = new String("Techno");
Each time a new object is created.
-------------------------------------------------------------------------------------------------------------------
You can change the value but not in the same memory [Link] you change the value, you need to capture it else in the
existing memory it will not get updated.
Immutable : Value cannot be changed in the same memory location. To change the value, you need to capture it in a new
memory location.
-------------------------------------------------------------------------------------------------------------------
Garbage Collector:
When the reference count is zero, then it is ready for Garbage collection and will be removed from memory when JVM runs the
garbage collection [Link] String is immutable ?
To implement SCP concept, we need to make String as immutable.
Hence, there is no impact in the SCP, when multiple references are pointing to the same value.
Que: How many time the memory gets initialized?
String str1 = "Hi" // SCP
String str2 = new String("Hi"); // Heap memory, new object is created
String str3 = str2; // str3 will start pointing to where str2 is pointing
String str4 ="Hi"; //exists in SCP, will point there
String str5 = new String("Hi"); // Heap memory, new object is created
String str6 = "HI"; // creates a new memory in SCP
Ans: 4
-------------------------------------------------------------------------------------------------------------------
Imp: When you concatenate two Strings using '+' operator then it returns an object.
-------------------------------------------------------------------------------------------------------------------
Que: Can we typecast from String to StringBuilder or StringBuffer?
Ans: We cannot typecast from String to StringBuilder / StringBuffer and vise versa as they are not in parent -child relationship. If
we do so, will get [Link] avoid this we need to use the toString() method of String class which converts it to
String and then the StringBuilder or StringBuffer can be stored in String.
Example:
String input = "technocredits";
StringBuilder sb = new StringBuilder(input);
String name = [Link]().toString();
Java- April 2025 Page 7