Strings in java

Let’s learn strings in java.

Strings in java

In java, string is an object. It is sequence of character values enclosed by double quotes.

java.lang.String class is used to create string object.

For example:

String name = “Sachin”;

String class implements Serializable, Comparable and CharSequence interfaces.

Syntax:

public final class String

NOTE:

String object is immutable.


Below are three classes to create Strings in java.

  • String class
  • StringBuilder class
  • StringBuffer class

There are two ways to string object in java. They are,

  • by string literal.
  • by new keyword.

When you create a string object, two objects are created, one in heap memory area and another in string constant pool. String object reference points to heap memory area.


String constant pool in java

String constant pool in java or string literal pool is a unique memory location inside heap area where string literal objects are stored.

Let’s understand string constant pool.

strings in java

Let’s create string object using “new” keyword.

String str = new String(“Hello”);

In the above statement I’m creating string object “str” and this object gets memory allocation in heap area because of “new” keyword.

Meanwhile there is string literal in above statement, i.e, “Hello”.

This string literal gets memory allocation in String constant pool area. Hence creating another object.

JVM internally creates reference variable internally for “Hello” object in string constant pool.

If you notice we are creating two objects by writing one single statement.

Now let’s create string object using string literal like this,

String s = “World”;

Here i’m creating a string literal “World”. This creates object in string constant pool.

By creating string object using string literal, object will not be created in heap area.

In case of string literal we are creating only one object in string constant pool.

While using “new” keyword we are creating two string objects one in heap area and another in string constant pool.

This is the reason string literal is preferred in creating string objects.

NOTE:

If there is already a string literal “Hello” in the string constant pool, then it will not create new string object in string constant pool with string literal “Hello”.

If there is no string literal “Hello” in string constant pool, then two objects will be created.

One in heap area and another in string constant pool.

Until java 1.6 version string constant pool was present in method area of memory area.

After java 1.6 version it was shifted to heap area.

Refer – preface to java virtual machine and architecture

NOTE: Garbage collection is not applicable for string objects present in string literal pool since JVM internally maintain a reference.


why string is immutable in java: Strings in java

String is immutable in java because String objects are cached in string constant pool.

String object once created cannot be changed; its value can’t be changed.

If string object is changed then it creates a new string object.

Let’s see an example on why string is immutable in java.

public class ImmutableStringExample
{
   public static void main(String[] args)
   {
      // string literal
      String str = "Hello";
      System.out.println(str);
      str = str.concat(" world");
      System.out.println(str);
      str = str.concat(" java");
      System.out.println(str);
   }
}


Output:

Hello
Hello world
Hello world java


String class methods in java: Strings in java

MethodDescription
static String valueOf(int value)converts given type into string. This is an overloaded method.
String trim()removes beginning and ending spaces of this string.
String toUpperCase(Locale l)returns a string in uppercase using specified locale.
String toUpperCase()returns a string in uppercase.
String toLowerCase(Locale l)returns a string in lowercase using specified locale.
String toLowerCase()returns a string in lowercase.
int indexOf(String substring, int fromIndex)returns the specified substring index starting with given index.
int indexOf(String substring)returns the specified substring index.
int indexOf(int ch, int fromIndex)returns the specified char value index starting with given index.
int indexOf(int ch)returns the specified char value index.
String intern()returns an interned string.
String[] split(String regex, int limit)returns a split string matching regex and limit.
String[] split(String regex)returns a split string matching regex.
static String equalsIgnoreCase(String another)compares another string. It doesn’t check case.
String replace(CharSequence old, CharSequence new)replaces all occurrences of the specified CharSequence.
String replace(char old, char new)replaces all occurrences of the specified char value.
String concat(String str)concatenates the specified string.
boolean isEmpty()checks if string is empty.
boolean equals(Object another)checks the equality of string with the given object.
boolean contains(CharSequence s)returns true or false after matching the sequence of char value.
String substring(int beginIndex)returns substring for given begin index.
char charAt(int index)returns char value for the particular index
int length()returns string length
char charAt(int index)returns char value for particular index.
static String format(String format, Object… args)returns formatted string.
static String format(Locale l, String format, Object… args)returns formatted string with given locale.
String substring(int beginIndex, int endIndex)returns substring for given begin index and end index.
static String join(CharSequence delimiter, CharSequence… elements)returns joined string.
static String join(CharSequence delimiter, Iterable elements)returns joined string.
int indexOf(String substring)returns the specified substring index.

Java Strings – special characters

Escape characterOutputDescription
\’single quote
\”double quote
\\\backslash escape character

Let’s see an example on these special characters.

public class SpecialCharactersExample
{
   public static void main(String[] args)
   {
      // sequence \" inserts double quote
      String str1 = "The purpose of our \"lives\" is to be happy.";
      System.out.println(str1);
      // sequence \' inserts single quote
      String str2 = "It\'s monday blues.";
      System.out.println(str2);
      // sequence \ inserts a single backslash
      String str3 = "This character \ is called backslash.";
      System.out.println(str3);
   }
}


Output:

The purpose of our “lives” is to be happy.
It’s monday blues.
This character \ is called backslash.


Other escape sequences in java

CodeOutput
\nnew line
\rcarriage return
\ttab
\bbackspace
\fform feed