Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
java
jvm
communitycreator

What are strings in Java?

Tarun Telang

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.

Strings as array of characters

Interfaces in 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.

Interfaces implemented by the String class

In Java, strings are immutabletheir object cannot be modified after it is initialized. The 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 JVMJava Virtual Machine.

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.

RELATED TAGS

string
java
jvm
communitycreator
RELATED COURSES

View all Courses

Keep Exploring