In Java
, a String
is a sequence of characters represented as an instance of the java.lang.String
class.
Internally, strings
are represented as an array of Unicode characters
indexed starting with 0
, 1
, 2
, and so on, from left to right.
All the operations that we use in an array can also be performed on String
objects.
string
The String
class implements CharSequence
, Serializable
, and Comparable
interfaces. Below are the details of these interfaces:
The CharSequence
interface provides charAt()
used to access the char value at the specified index.
The Comparable
interface provides the compareTo()
method to compare the objects.
The Serializable
interface is a markup interface as it does not provide any methods or constants.
The
Serializable
interface simply provides information to the JVM at run-time to enable serialization and deserialization.
In Java
, strings
are string
can be initialized at the time of object creation. Thereafter, an entirely new string
object is created in the memory whenever the’ string’ object is modified.
String
literals are stored in the Java
heap memory storage area known as the String Pool.
String <string_variable> = "<char_sequence>";
String <string_variable> = new String("<char_sequence>");
String str = "Hello";
String str1 = new String("World");
In the first case, the string
object named "Hello"
is created as a literal and stored in the String
pool, which results in optimization of memory by
On the other hand,"World"
is created using the new
operator with the string
object. An entirely new memory will be allocated dynamically, and this string
would not be added to the String
pool.