Strings In Java
In java, String is an Object used to store sequence of characters. String also is a class provided by Java, so it is a reference type.
Strings (String literals) are stored in special memory called String Constant Pool. If the same literal already exists in the pool, Java reuses the existing String object instead of creating another one.
Why Strings are immutable in java?
Strings are immutable for security and memory efficiency. So whenever we change the existing string, it actually creates a new Object in java.
So inoreder to overcome this we have StringBuffer and StringBuilder. We will detaily look that into this blog.
Different ways to create Strings in java
There are two ways of we can create Strings in java,
- String Literal
Basically String literal is a sequence of characters enclosed with double quotes. For memory efficiency, String literals are stored in special memory called String Constant Pool(SCP).
Example,
String str="Joy boy";2. Using new keyword
Using new keyword, we can also create strings in java but, it is completly different from String literals. When we use new key word, the strings are created inside the heap not inside the String Constant Pool.
Example,
String str=new String("Vignesh");How Strings are stored in java memory?
Strings are stored in special memory called String Constant Pool. Which is located inside of the heap. lets understand, why string is stored in string constant pool through small program.
public class Demo {
public static void main(String[] args) {
String name="Vignesh";
String str="Vignesh";
System.out.println("Name : "+name);
System.out.println("Str : "+str);
System.out.println(str==name);
name="Ram";
System.out.println("Name : "+name);
System.out.println("Str : "+str);
System.out.println(str==name);
}
}OUTPUT
Name : Vignesh
Str : Vignesh
true
Name : Ram
Str : Vignesh
falsename is a reference variable stored in the stack memory, and it refers to a String object stored in the heap memory. The String literal “Vignesh” is stored in the String Constant Pool (SCP), which is part of the heap in modern JVM implementations.
Here both name and str is pointing to the same Object inside the SCP. So when we try to change name into something else like “Ram”, it only creates new object inside the SCP then, name variable is pointing to “Ram”. This is why Strings are immutable in java.
For instance, Imagine you are working in a big project, two users names are similar like “Vignesh”. If one user want to change their name into “Ram” if it is not immutable this also affects the another user. So this why strings are immutable in java.
Both name and str initially pointing to the same value “Vignesh”. When we change the value of name into “Ram”, java creates the new Object inside the heap.
If any String reference variable is not pointing to an object, that object will be automatically removed by the Garbage Collector.
Using new key word
When we use new keyword to create a String Object, It creates the new object outside the SCP but inside the Heap. So when we used to == compare the values it returns false.
.equals() vs == in java
- .equals()
In java, .equals() is a method in String class that compares the content of the two String object. So use this method, when you want to compare the content(values).
2. ==
== compares the references and checks whether both references refer to the same object.
public class Demo {
public static void main(String[] args) {
String name = "Vignesh";
String str = new String("Vignesh");
System.out.println("Using .equals() : " + name.equals(str));
System.out.println("Using == : " + (name == str));
}
}Output
Using .equals() : true
Using == : falseStringBuilder and StringBuffer in java
StringBuilder and StringBuffer are classes, which helps to create mutable sequence of strings Object in java. StringBuilder and StringBuffer objects are stored in the heap. Compare with String it is very fast, when a String is modified, it creates a new String Object cause String is immutable.
Get Vignesh’s stories in your inbox
Join Medium for free to get updates from this writer.
StringBuilder and StringBuffer both have similar methods for modifying Strings. But StringBuilder is not thread safe, so it is faster than the StringBuffer. StringBuffer is thread safe (it executes the operations synchronously) because its methods are synchronized.
Different Ways to create StringBuilder Object in Java
- Using default constructor (StringBuilder()):
Creates an empty StringBuilder with default capacity of size 16.
Example,
StringBuilder sb = new StringBuilder(); //default size 162. Using initial capacity (StringBuilder(10)) :
Creates a new empty StringBuilder with pre-allocated capacity of some size using new StringBuilder(10).
StringBuilder sb = new StringBuilder(10); 3. Using initial String (StringBuilder(“Hello”)):
new StringBuilder(“Hello”) has an initial capacity of 16 + length of the String, so for “Hello” the capacity is 21
StringBuilder sb = new StringBuilder("Hello"); //capcity is 21Methods in StringBuider and StringBuffer
StringBuilder and StringBuffer both have similar methods for modifying Strings.
append() : used to add the String at the end of the StringBuilder.
sb.append("Hello");Insert(): used to insert a text at the specific position
sb.insert(0, "Hi ");replace(): it replaces characters in a specified range
sb.replace(0, 5, "Java");delete(): Used to delete characters from the specified start index to the specified end index.
sb.delete(0,2);deleteCharAt(): used to delete one specific character in the Builder
sb.deleteCharAt(2);reverse(): reverse() method is used to reverse the String
sb.reverse();charAt(): used to get single character of a specified index
sb.charAt(0);setCharAt(): used to change single character of a specified index
sb.setCharAt(0, 'J');length(): It returns the number of characters in the string
sb.length();capacity(): It returns the current capacity
sb.capacity();indexOf(): It finds the first occurence and return the index
sb.indexOf("Java");lastIndexOf(): It finds the last occurence and return the index
sb.lastIndexOf("Java");toString(): Used to convert builder into String
String str1=sb.toString();
String str2=String.valueOf(sb); // this also used convert builder into String









