Strings
Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created.
Syntax:
String str = "abcd";
Memory allotment of String
Whenever a String Object is created as a literal, the object will be created in String constant pool. This allows JVM to optimize the initialization of String literal.
The string can also be declared using new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in heap. This string will not be added to String constant pool.
Example:
String str = new String("abcd");
An example that shows how to declare String
import java.io.;
import java.lang.;
class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String s = "GeeksforGeeks";
// Prints the String.
System.out.println("String s = " + s);
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
// Prints the String.
System.out.println("String s1 = " + s1);
}
}
Output:
String s = GeeksforGeeks
String s1 = GeeksforGeeks
Top comments (1)
Nice post!
I would like to add just one detail:
It is true that Strings are backed internally by a char array, but only up to Java 8.
As of Java 9, Strings are backed by a byte array.
You can see this in the source code: