What are strings in Java?
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.
Interfaces in string
The String class implements CharSequence, Serializable, and Comparable interfaces. Below are the details of these interfaces:
-
The
CharSequenceinterface providescharAt()used to access the char value at the specified index. -
The
Comparableinterface provides thecompareTo()method to compare the objects. -
The
Serializableinterface is a markup interface as it does not provide any methods or constants.
The
Serializableinterface 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.
Syntax
String <string_variable> = "<char_sequence>";
String <string_variable> = new String("<char_sequence>");
Code
String str = "Hello";
String str1 = new String("World");
Explanation
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.