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.

Also read – reverse a string in java

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 i)returns the string representation of the int argument.
String trim()returns a copy of the string, with leading and trailing whitespace omitted.
String toUpperCase(Locale locale)converts all of the characters in this String to upper case using the rules of the given Locale.
String toUpperCase()converts all of the characters in this String to upper case using the rules of the default locale.
String toLowerCase(Locale locale)converts all of the characters in this String to lower case using the rules of the given Locale.
String toLowerCase()converts all of the characters in this String to lower case using the rules of the default locale.
int indexOf(String str, int fromIndex)returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
int indexOf(String str)returns the index within this string of the first occurrence of the specified substring.
int indexOf(int ch, int fromIndex)returns the specified char value index starting with given index.
int indexOf(int ch)returns the index within this string of the first occurrence of the specified character.
String intern()returns a canonical representation for the string object.
String[] split(String regex, int limit)Splits this string around matches of the given regular expression.
String[] split(String regex)Splits this string around matches of the given regular expression.
boolean String equalsIgnoreCase(String anotherString)Compares this String to another String, ignoring case considerations.
String replace(CharSequence target, CharSequence replacement)Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replace(char oldChar, char newChar)Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String concat(String str)Concatenates the specified string to the end of this string.
boolean isEmpty()Returns true if, and only if, length() is 0.
boolean equals(Object anObject)Compares this string to the specified object.
boolean contains(CharSequence s)Returns true if and only if this string contains the specified sequence of char values.
String substring(int beginIndex)Returns a new string that is a substring of this string.
char charAt(int index)Returns the char value at the specified index.
int length()Returns the length of this string.
char charAt(int index)Returns the char value at the specified index.
static String format(String format, Object… args)Returns a formatted string using the specified format string and arguments.
static String format(Locale l, String format, Object… args)Returns a formatted string using the specified locale, format string, and arguments.
String substring(int beginIndex, int endIndex)Returns a new string that is a substring of this string.

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