Java String Class

In this short post, we are going to discuss the different features and characteristics of the Java String class.

Introduction

We often deal with a lot of text in many applications. It can be a simple “welcome”; message to a website. Strings are a group of characters enclosed between double quotes (” “) like Welcome“, “success”, “Hello@!2” etc. The Java String is an immutable class in the default Java package java.lang which is available for every Java file (You don’t need an import statement for this.). Let’s take a closer look at a few important aspects of the String class.

1. Creating a String

There are 2 ways to create a String Object.

  1. Using the new operator.
  2. String literal.

1.1 The new Operator

String string=new String("welcome");

1.2 String Literal

Assigning the String literal value directly using the assignment(=) operator

String string="welcome";

The former will always create a new String object using the new operator but when literal values are directly assigned as shown in the second way to a String it may or may not create an object due to the concept of String constant pooling in java.

2. String Constant Pool

Memory allocation happens for any object irrespective of String class when created using the new operator String string=new String("Hello");. String Pool provides a better memory allocation when using Java String literal values. When a String object created directly by assigning literal values then the memory allocation happens only once by the JVM so, that the same reference can be referenced again when another String object with the same literal value requested instead of creating a new String object.

Java String

Above shows the Java String object created using new operator being referenced by the reference variable string in the memory Heap. Let’s take a look at the memory allocation when using String literal

Java String literal

This shows the String object being referenced by two reference variables string1, string2. When the JVM encounters the statement String string1<b>=</b>"Hello" it creates the object in the String constant pool whose reference may be re-used when another String object with the same String literal value is requested so the statement String string2="Hello"; will not create a new object and will use the existing object in the String constant pool. Here is one example for your reference:

public class StringExample {
 public static void main(String args[]) {

  //creating a string by java string literal 
  String str1 = "javadevjournal";

  //creating another Java String using new keyword 
  String str2 = new String("Java String example Using new keyword");

  //Displaying all the strings
  System.out.println(str1);
  System.out.println(str2);

 }
}

3. Java String Methods

Let’s take a look at some of the most important methods available in the String class. While it seems that this class is modifying the String object, but keep in mind that String class is Immutable which means cannot be modified after Initializing.

3.1 The charAt( int index) Method

Method charAt(int index) query the String for a character at a specific place. To understand, let’s take an example of this String literal.

String string="javadevjournal";

So, for the above String, the method string.charAt(2) returns the character at index 2 which is ‘v’. Notice that the Index for strings starts from 0.

3.2 The indexOf(char c) Method

The methodindexOf() has multiple overloaded versions which are used to get the index of the argument passed to the method.

String string="javadevjournal"

string.indexOf('v') returns the index 2 which is the first index of ‘v ‘ stored in the string.string.indexOf('V',3) returns the index 6, as the second argument is used to specify the start position to search which is 3.The string.indexOf("dev") returns the starting index of substring “dev” in the string “javadevjournal” which returns the index 4. All the indexOf() methods return -1 when the substring or the character searching for is not found.

3.3 The substring(int index) Method

This method returns the substring from the index specified until the end position of the string. Let’s take the same “javadevjournal” String for our example.The string.substring(2) returns substring “vadevjournal”.we can also use the overloaded method with an offset in the parameter like string.substring(1,4) which returns “ava”.Note that the second argument is the offset, not the index assuming that the string characters count to start with 1 but not with 0

3.4 The trim() Method

This method is useful to trim the leading and trailing spaces if any in the String. Let’s take following String for our example.

String string="  javadevjournal  "

string.trim() prints the output as “javadevjournal” removing the spaces at the start and end of the string. This method cannot remove spaces between the string.

3.5 The length() Method

The length() method returns the length of the String. If we run this against our sample String “javadevjournal”, this method returns length as 14.

3.6 The contact() Method

This method is useful to concatenate the strings.Let’s take a look at the following example for better understanding.

String string="javadev"; string.concat("journal");

While running this example, it prints the output as “javadevjournal”.All the above methods return new String objects and won’t modify the existing initialized String objects as they are immutable. For example, if you print the string used in the concat() method example after concatenating it still prints “javadev”.

Java 8 came with a number of improvement. Refer to the Java 8 StringJoiner for more detail.

Summary

In this posts, we talk about the different features of the Java String class. Strings are immutable objects and cannot be modified once initialized. String class has many built-in methods which return new String object instead of modifying the existing one. String constant pool helps avoiding java.lang.OutOfMemoryError by using efficient memory allocation algorithm if using the same String literals. Refer to String (JDK Documentation)  for more detail.

Scroll to Top