Java Tutorial



Java Tutorial

String in Java


The concept of string in Java is taught in any beginner Java programming class. It is an instrumental concept in different coding scenarios and a must-have in your Java knowledge arsenal. This tutorial provides an in-depth guide to the various concepts of strings in Java.


Java uses strings for various tasks, such as text data storage and manipulation, user input handling, file processing, network connection, and more. Java provides many inbuilt functions to work on strings.

Understanding the concept of strings is crucial for mastery of Java programming.

What Are Strings in Java?

A string in Java is a data type used to store a sequence of characters. It acts the same way as an array does in Java.

How to Create a String Object?

There are two ways we can create strings in Java. Let us look at the Java string syntax:

  • String Literal: In this method, double quotes are used to assign a string value to a variable directly. Java constructs a string object and assigns it to the variable automatically. The string pool stores string literals for effective memory usage and simple reference sharing.

Example syntax: 

String myString = "Hello, World!";
myString = "Java Programming";
  • Using the new keyword: In this method, you construct a new instance of the string class using the string constructor and the new keyword. Regardless of whether the same value already exists in the string pool, this generates a unique string object in memory. The new keyword is used less frequently to create strings than string literals.

Example syntax: 

String myString = new String("Hello, World!");
myString = new String("Java Programming");

Interfaces and Classes in Strings in Java

A class in Java refers to a group of objects with similar properties. Different objects in a class may show different attributes and properties described by the class. A class is also called a blueprint for the creation of objects.

An interface in Java can be called the blueprint of a class and has fields like static, final, and public. The method body can not be defined in Java. An interface, unlike an abstract class, can not be instantiated.

Interfaces are used in Java for the following reasons:

  • Interfaces are used to achieve abstraction in Java.

  • Multiple inheritances can also be achieved in Java using interfaces. 

  • Interface in Java is used to achieve loose coupling.

Let us look at a Java string program with output.


import java.util.StringTokenizer;
public class StringInterfacesAndClassesExample {
    public static void main(String[] args) {
        // Using CharSequence interface
        CharSequence charSequence = "Hello, World!";
        int length = charSequence.length();
        char firstChar = charSequence.charAt(0);
        CharSequence subSequence = charSequence.subSequence(7, 12);
        System.out.println("Length: " + length);
        System.out.println("First Character: " + firstChar);
        System.out.println("Subsequence: " + subSequence);
        // Using StringBuilder class
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(" ");
        String result = stringBuilder.toString();
        System.out.println("StringBuilder result: " + result);
        // Using StringTokenizer class
        String sentence = "The quick brown fox jumps over the lazy dog";
        StringTokenizer tokenizer = new StringTokenizer(sentence);
        System.out.println("Tokenized sentence:");
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();

In this example, we create an instance of CharSequence and demonstrate its length(), charAt(), and subSequence() methods. Then, we use the StringBuilder class to efficiently concatenate strings. Finally, we tokenize a sentence using the StringTokenizer class to split it into individual words.

CharSequence Interface

A sequence of characters is represented with the help of the CharSequence interface in Java. It is implemented with the help of

  • String class

  • StringBuffer class

  • StringBuilder class

The string is immutable in Java, meaning it can not be modified. StringBuffer and StringBuilder classes are used for mutable strings.

StringBuilder and StringBuffer Classes

The StringBuilder and StringBuffer classes provide mutable sequences of characters. They are commonly used for efficient string concatenation or manipulation.

StringTokenizer Class

The StringTokenizer class allows you to tokenize a string into individual tokens based on a specified delimiter.

Memory Allotment of String

Strings in Java are stored in a heap storage area called the string pool. String Intern pool and String Constant pool are other names of String pool. Java String class maintains the string pool and is empty by default, just like any other object storage. 

When you initialize a new string, JVM checks if the same string is already present in the string pool before allotting space to it. If yes, it just stores a reference to the previously stored string to save resources.

Why Did the String Pool Move From PerGen to the Normal Heap Area?

In Java 8, the String pool was transferred from the Permanent Generation (PermGen) area to the standard heap area. This modification was developed to address problems with PermGen space, a fixed-size memory space that holds class metadata, interned strings, and other JVM-specific information.

How Do Strings Work in Java?

A string works the same way an array of characters do. The String class in Java provides a lot of default methods like concat(), compare(), replace(), compareTo(), substring(), and more. With the help of these predefined functions, it is very convenient to operate on strings in Java.

Java String Examples

Strings in Java are an immutable data type that stores a sequence of characters. Here we will discuss an example.

Let us look at this piece of code

String s1 = “computer”;

Here, the name of the string is s1, and the value stored in it is “computer.” The compiler treats the string like an array and puts the characters of “computer” in different memory locations in a series. If we take this example, the character ‘c’ is stored at position 0, ‘o’ is stored at position 1, and so on.

Example of Strings in Java

Here is an example of using strings in Java:

public class String1 {
    public static void main(String[] args) {
        String message = "Hello, World!";
       int length = message.length();
        System.out.println("Length: " + length);
        String name = "Alice";
        String greeting = message + " My name is " + name;
        System.out.println("Greeting: " + greeting);
        String substring = message.substring(7, 12);
        System.out.println("Substring: " + substring);
        String uppercase = message.toUpperCase();
        String lowercase = message.toLowerCase();
        System.out.println("Uppercase: " + uppercase);
        System.out.println("Lowercase: " + lowercase);
        String str1 = "apple";
        String str2 = "banana";
        int result = str1.compareTo(str2);
        System.out.println("Comparison result: " + result);
        String sentence = "I love programming";
        String[] words = sentence.split(" ");
        System.out.println("Words: ");
        for (String word : words) {
        String paddedString = "   Hello   ";
        String trimmedString = paddedString.trim();
        System.out.println("Trimmed string: " + trimmedString);
        String replacedString = message.replace('o', 'a');
        System.out.println("Replaced string: " + replacedString);

Methods of Java Strings

There are numerous string methods in Java which make Java programming a lot easier. Let us look at some string methods in Java with examples.

int length() method

The int length() method is used to measure the size of the string or how many characters the string consists of. The method has an integer return type and always returns the output in a whole number.

char chatAt(int index) method

The char charAt(int index) method returns the character present at a specific point in an array. This method has a character return type and always returns characters. The position at which the method returns the character can be defined in the variable named index by the programmer.

String concat(String string1) method

The String concat(String string1) method adds a string at the end of another string. Here, it will add the string string1 at the end of another pre-existing desired string. 

This method has a string return type and thus returns a string.

String substring(int beginIndex, int endIndex[optional]) method

This method is used to extract a substring from an already declared string. We can derive the new string from a desired start point by mentioning it in the variable int beginIndex. If the endpoint is not specified at int endIndex, the method assumes the end to be till the end of the array. This method has a string return type.

String equals(String anotherString) method

The String equals(String anotherString) method is used to compare whether or not two strings have the same contents. If they are the same, the method returns true. Otherwise, it returns false. It is a boolean-type method and only returns true or false.

String contains(String substring) method

The contains() method is used to check if the provided substring is present inside the parent string we are checking in. The user can put the value of what they want to search in the substring variable in Java. This method also has a boolean data type and only returns true or false. 

String join(CharSequence joiner, String st1, String st2, String st3......)) method

The String class, introduced in Java 8, contains a static method called String.join(). With a designated delimiter, you can concatenate multiple strings.

int compareTo(String string1, String string2) method

A static method in Java's String class is int compareTo(String string1, String string2). It performs a lexical comparison between two strings and outputs an integer value representing the relative order of the strings.

String toUpperCase() method

The String class in Java contains the method toUpperCase(). It creates a new string with the uppercase representation after changing every character in a string to uppercase. The return type of this method is a string.

String toLowerCase() method

Similarly, The String class in Java includes a built-in method called toLowerCase(). It gives back a new string that has all the characters in lowercase. This method also has the return type string.

String trim() method

The trim() method in Java removes any leading or trailing whitespaces in the string. This means the trim() method checks the beginning and end of the string. It stops scanning when it finds any white spaces from either end of the string. It does not hamper the orientation of spaces inside a string but only on the extremities.

String replace(char oldChar, char newChar) method

The String class in Java includes a built-in method called replace(char oldChar, char newChar). Here, oldChar is a variable that pre-exists in the string and is replaced by newChar, which is user-defined. All instances of the oldChar are replaced with the newChar in the new string returned. This method also has a string return type. 

Concatenating String

Concatenating means linking multiple things together. Similarly, when we concatenate multiple strings in Java, they make a new string with the combination of two or more previously defined strings.

We can concatenate strings in Java using two methods:

  • By using the “+” operator

  • By using the “concat()” string manipulation method.

Creating Format Strings

Java format strings are created using the String.format() method. Java's String.format() function and the printf() method from the System.out or PrintStream class are used to create format strings. By mixing static text with placeholders for values that will be inserted during runtime, format strings enable you to build dynamic strings.

Escape character () in Java String

A backslash (/) is used in Java to indicate the escape character. It is applied when a string literal has to contain special characters or escape sequences. Here are a few often utilized escape mechanisms:

  • \n represents a new line.

  • \” represents using double quotes as a character in the string.

  • \\ represents the use of a backslash character in the string

  • \’ represents the use of a single quote character in a string

  • \b represents a backspace character

  • \r represents a carriage return character

  • \t represents a tab character

  • \f represents a form feed character

Java Strings: Mutable or Immutable

A common question most beginner-level Java learners face is, “ Why string is immutable in Java?” 

A string in Java, by default, is an immutable data type in Java. This means the contents in a string cannot be altered in the same instance of the string. A new string instance is created in the string pool whenever we alter or mutate a string. The state of a mutable class can also not be changed.

Objects in Java whose values can be changed after initialization in Java are called mutable objects. The field, state, and values can be changed; while doing so, no new object will be created. It will alter the value of the existing object. StringBuilder() and StringBuffer() in Java are examples of methods by which mutable strings can be created.


Strings are essential to Java programming since they are the primary data type for textual information representation. Throughout this tutorial, we have examined the main characteristics and capabilities of strings in Java, learning more about their adaptability and significance. This should serve as the foundation for you to master more advanced Java programming concepts.


1. What is string interning in Java?

String interning in Java refers to storing string literals in a string pool to save the system's resources.

2. How do you compare strings in Java?

You can compare strings in Java using the compareTo() and equals() methods.

3. What are some best practices for working with strings in Java?

Using StringBuilder and being mindful of memory usage is a good practice for using strings in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *