String in Java

The general definition of String is a sequence of character. In other word you can say string is an alphanumeric value, which means it can be alphabets or numbers. String in Java is an object. Java provides String class to store the string values. The string class implements the three classes (Serializable, Comparable and CharSequence).

String in Java
String Class in Java

Ways to create String variable

There are two ways to create string variables in Java.

  • String literal – allocate space in String constant pool
  • new String () – allocate space in Heap memory
String s1 = "Hi"; // String literal - allocate space in the string constant pool
String s2 = "Hi"; // String literal - create a reference of s1

String s3 = new String("Hi"); // allocate space in heap memory
String s4 = s3.intern(); // creates a reference of s1

Immutable

In Java, String is immutable, which means when you create the String object JVM allocate space in String constant pool. When you change the value in the same object JVM will allocate new space in String constant pool.

String constant pool and heap memory
String pool

String Buffer and String Builder

In Java String class in immutable, It means JVM will be allocated the new space in the string constant pool whenever you change the value of string objects. So Java provides the two classes to make string objects are mutable. Mutable means whenever you change the values in string object, the JVM will not be allocated the new space. And when you create string object using string buffer or string builder, the JVM will be allocated space in Heap memory.

string, string builder and string buffer

If you want to know the difference between String, string buffer and string builder please refer this blog https://samplecoder.com/string-vs-string-builder-vs-string-buffer

One Comment on “String in Java”

Leave a Reply

Your email address will not be published.