Strings in java

Strings are a sequence of characters enclosed within the double quotes which include alphabets, numbers, special characters and so on. Strings are objects in Java, which means strings are not a primitive data type.

The Architecture of Strings :

We can form strings using below classes; all three classes implement CharSequence interface and extends Object Class :

  • String
  • StringBuffer
  • StringBuilder

Lets us discuss String Class first.

String Class in Java

String class implements the CharSequence interface and extends Object class; the Object class is the topmost class in java.

A string is represented with "" (double quotes). A string is immutable, which means once we create a string object, we cannot modify the String object.

The class String includes methods for examining individual characters of the String, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or lowercase.

We can create strings in two methods :

  • Double quotes method (most preferred method)
  • String object method
Double quotes method :

A string is created by enclosing the string inside double quotes; below are few processes that happen when we use double quotes to create a string.

  1. JVM checks String Constant pool for any value which same as what we are trying to create.
  2. If yes, point that string object reference to the variable that we are trying to create.
  3. If no, JVM creates a new string object in String constant pool.
public static void main(String[] args) {
    // create chercher tech string
    String firstString = "CherCher Tech";
    System.out.println("String we created : "+firstString);

String object method :

We can also create a string by creating an object of String class. We have to call the String class constructor to create the string, and that creates the string in the non-constant pool in the String pool.

JVM will not check for the duplicate strings if we use String Constructor to create a string. So there can be duplicate strings in the non-constant pool.

public class StringExample2 {
    public static void main(String[] args) {
        // create the string
        String secondString = new String("Pavan kumar N");
        // print the string
        System.out.println("String created is : "+secondString);

What is String pool :

String Pool is a pool of string values that are available to other parts of the program. String pool can be divided into two parts

  • Constant String pool
  • Non-Constant String pool


String Constant Pool :

String constant pool located inside a section of memory is called the heap. This is a part of memory that is used for run-time operations, working with classes and objects.

String constant pool does not allow users to create duplicate strings. If the user tries to create a duplicate string using "(double quotes), then the string pool returns the address of the existing string.

So at any given time, the Constant String pool will contain unique values, and also users may not feel any difference with operations.

In the below example, we will create two strings, and we will verify the address of those strings.

public class StringExample3 {
    public static void main(String[] args) {
        String str1 = "checrcher tech";
        String str2 = "checrcher tech";
        // get the address of the strings
        System.out.println("Address of the str1 : "+System.identityHashCode(str1));
        System.out.println("Address of the str2 : "+System.identityHashCode(str2));


Non-Constant String Pool

Non-constant string pool will allow the user to create duplicates. Below example print the address of the string created.

public class StringExample4 {
    public static void main(String[] args) {
        String str3 = new String("pavan kumar");
        String str4 = new String("pavan kumar");
        // get the address of the strings
        System.out.println("Address of the str3 : "+System.identityHashCode(str3));
        System.out.println("Address of the str4 : "+System.identityHashCode(str4));


Compare Strings

We cannot compare strings using '==' relational operator, as '==' operator tries to compare the address of the object. But most of the time, strings may not be stored in the same object so the address will be different for each string. We should use equals() present in the String object to compare two strings.

public static void main(String[] args) {
    String str1 = new String("CherCher tech");
    String str2 = "CherCher tech";
    System.out.println("Comparision using '==' : " + (str1 == str2));
    System.out.println("Comparision using 'equals()' : " +(str1.equals(str2)));


Really, Cannot we compare Strings using '==' : We can compare the strings using '==' sign as well, but with one condition, Strings must have created using "".

In this case also '==' tries to compare the address but as the constant pool will let unique values to present, so the address will be the same when the content of the strings is the same.

public static void main(String[] args) {
    String s3 = "CherCher tech";
    String s4 = "CherCher tech";

    System.out.println("Comparision using '==' : " + (s3 == s4));
    System.out.println("Comparision using 'equals()' : " +(s3.equals(s4)));


Useful methods in String class

There are so many methods present in String, but we will learn about the most used methods of String.

Length :

length method return number of characters present in the string, it returns an integer value.

public static void main(String[] args) {
    String str = "";
    System.out.println("String Length : "+str.length());



charAt method returns a character at a particular position; in java, the index starts from 0. If we want to get 5th element, then we have to query for 4th index

public static void main(String[] args) {
    String str = "";
    // index starts from zero
    System.out.println("Char at 5th element : "+str.charAt(4));


Concat :

concat is nothing but adding two or more strings, concat() method helps the user to add two string into one string. This method will not disturb the existing strings, and it will create a new string with concatenation and returns it.

public static void main(String[] args) {
    String str = "CherCher";
    String str2 = "Tech";
    String abc = str.concat(str2);

    System.out.println("String  : "+str);
    System.out.println("String 2  : "+str2);
    System.out.println("String concat : "+abc);


startsWith :

startsWith method verifies whether the String starts with given substring or not. This return a boolean value, true if the String starts with given substring else false.

public static void main(String[] args) {
    String str = "";
    System.out.println("Starts with Cher : " +str.startsWith("Cher"));
    System.out.println("Starts with ABC : " +str.startsWith("ABC"));


endsWith :

endsWith method verifies whether the String ends with given substring or not, endsWith method also returns a boolean value.

contains :

contains method verifies whether the String contains substring or not, the substring could be anywhere in the main string.

public static void main(String[] args) {
    String str = "";
    System.out.println("contains te : " +str.contains("te"));
    System.out.println("contains xyz : " +str.contains("xyz"));


equals :

equals() method compares the two string based on the content present in the string, if the content matches the equals() method returns true else false.

public static void main(String[] args) {
    String str = "";
    System.out.println("equals : " +str.equals(""));

isEmpty :

isEmpty method verifies whether given string is empty("") or not, empty means string with no value ("").

public static void main(String[] args) {
    String str = "";
    String str2 = "";
    System.out.println("str : " +str.isEmpty());
    System.out.println("str2 : " +str2.isEmpty());


replace :

replace method replaces the specified value with the given new value in all occurrences

public static void main(String[] args) {
    String str = "";
    System.out.println("After replace : " +str.replace("Cher", "AAAA"));


indexOf :

this method returns the first index of the given substring or character.

public static void main(String[] args) {
    String str = "";
    System.out.println("Index of he : " +str.indexOf("he"));


toUpperCase /toLowerCase :

We can convert the string into UPPERCASE or to lowercase using string methods.

public static void main(String[] args) {
    String str = "";
    System.out.println("UpperCase : " +str.toLowerCase());
    System.out.println("LowerCase : " +str.toUpperCase());


trim() :

the trim method removes the spaces at the starting and end of the string and returns the string without spaces at the ends.

public static void main(String[] args) {
    String str = "       ";
    System.out.println("Length before trim : " +str.length());
    System.out.println("Length after trim : " +str.trim().length());


Facts about Strings (not String Class) in Java

Below are the few facts about the strings in java; these are about strings only not about String class.

  1. A string is a derived / object type, not a primitive type like int, long, float, etc. Strings are objects in the java.
  2. We can create Mutable and immutable Strings in java
  3. String, StringBuffer, and StringBuilder are final, which means we can’t extend them. String, StringBuffer, and StringBuilder are members of the java.lang package.
  4. toString() is overridden in String, StringBuffer, and StringBuilder to print the string content
  5. String and StringBuffer objects are thread safety whereas StringBuilder objects are not thread safety
  6. Strings in java are backed by character array. You can retrieve this array using toCharArray() method of String class.
  7. Unlike in C and C++, Strings in java are not terminated with a null character
  8. A string is Designed to Optimize the Memory Usage, because which only the Constant String pool exists.
  9. Prefer StringBuilder when dealing with single threads only. Otherwise, if multiple threads could be accessing it, a StringBuffer (being synchronized) may be what you are after.
  10. A string is stored as UTF-16 characters, and maybe someday they will move to UTF-32 as well.

StringBuffer and StringBuilder

StringBuffer class is used to create mutable strings, which means we can alter the value of the string after we create it.

It represents a grow-able and append-able character sequence. Strings are formed using StringBuffer class when we have to make a lot of modifications to our string.

StringBuffer class methods are synchronized, so multiple threads cannot access the string value.

StringBuilder class is similar to the StringBuffer class; the only difference is StringBuilder class methods are not synchronized so that multiple threads can access the String value.

Constructors of StringBuffer : StringBuffer has 4 constructors which are :

  • StringBuffer ( )
  • StringBuffer ( int size )
  • StringBuffer ( String str )
  • StringBuffer ( charSequence[ ] ch )

StringBuffer() creates an empty string buffer and reserves room for 16 characters.

StringBuffer(int size) creates an empty string buffer, accepts an int value to generate room for character.

StringBuffer ( String str ) creates a given string buffer with characters room based on the length of the given string.

StringBuffer ( charSequence [ ] ch ) creates a string buffer based on the character array passed to the constructor.

Methods present in the StringBuffer and String Builder : Let's discuss a few methods present in the StringBuffer.

append : append() method updates the current value of the string, given string will be added at the end of the string.

We can append data types like boolean, char, int, long, Strings. Unlike String, string buffer modifies the current value and returns the self.

public static void main(String[] args) {
    StringBuffer str = new StringBuffer("CherCher");
    System.out.println("Str before append : "+str);
    // append the values
    System.out.println("Str after append : "+str);
    System.out.println("append with number: "+str);
    str.append(false<span class=&q
About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions