Java Strings – Learn the Essential Methods with its Syntax!

A String is defined as a sequence or an array of characters. We have already covered the basics of String in our article Java Data types. We know that String in Java is not a primitive data type; instead, it is an object of class String.

Java Strings are one of the most common and widely used classes in Java programming. The String is an array of characters, and since arrays are immutable in nature, a String is an immutable object, which means they are constant, and we cannot change them after creating the objects.

In this tutorial, we will learn the Java Strings in-depth with the help of the Java Wrapper class – String class.

Working with Strings in Java

Strings are a group of characters. In Java, you can work with the character data that is, a single character or a group of characters (Strings) in 4 different ways:

Character Class

It is a wrapper class whose objects hold single character data.

String Class

It is a class whose instances or objects can hold the unchanging or constant string (immutable String).

StringBuffer Class

Its instances or objects can hold mutable strings that can be changed or modified.

StringBuilder Class

Java StringBuilder class is similar to the StringBuffer class which holds a sequence of mutable Strings but is more versatile than StringBuffer class because it provides more modification features.

Creating Strings in Java

There are 2 ways of creating a String object:

By using a string literal

It is the most common way to create a String. Java String literal can be created just by using double-quotes.

For example –

String line = “Welcome to TechVidvan Java Tutorial” ;

Through this line, the compiler creates a String object in a String Pool with its value “Welcome to TechVidvan Java Tutorial”.

By using a “new” keyword

Java String can also be created by using a new keyword with the String constructor.

For example –

String line = new String(“Welcome to TechVidvan Java Tutorial”);

Code Snippet to understand the ways to create a string –

package com.TechVidvan.StringDemo;
public class StringTutorial
{
  public static void main(String args[])
  {
    String string1 = "Hello World";
    // declaring string using string literals
    String string2 = new String("This is TechVidvan Java Tutorial ");

    //declaring string using the new operator
    System.out.println(string1);
    System.out.println(string2);
  }
}

Output:

Hello World
This is TechVidvan Java Tutorial

Creating StringBuffers

StringBuffer objects are always created with a new operator. There are three ways by which you can create StringBuffer Objects:

1. Creating an empty StringBuffer object

StringBuffer sBuffer = new StringBuffer() ;

2. Creating and initializing the StringBuffer object

StringBuffer sBuffer = new StringBuffer( “ Hello World ” ) ;

3. Creating a StringBuffer object with an initial capacity equal to n

int n= 15;
StringBuffer sBuffer = new StringBuffer( n ) ;

Here, n is equal to 15 which is the number of characters. The object sBuffer has the capacity to hold 15 number of characters.

Methods of Java String Class

The methods of String class are used to obtain information about objects and are known as accessor methods. The String class provides many accessor methods that are used to perform operations on strings. We will cover some important methods of the String class in detail with the help of examples and code.

Java String Methods

1. int length() method

The length() method returns the length of the String that is, the number of characters in a String.

Syntax:

stringName.length( ) ;

Code to illustrate the use of length() method:

package com.TechVidvan.StringDemo;
public class LengthOfString
{
  public static void main(String args[])
  {
    String sentence = "This is a Tutorial on Strings";
    int len = sentence.length();
    System.out.println( "Length of sentence is : " + len );
  }
}

Output:

Length of sentence is : 29

Note: The length() method also includes whitespaces in the strings to calculate the length of the string.

2. char charAt(int index) method

We use charAt method to return a character value at a specified position (index) of a String.

Syntax:

stringName.charAt( index ) ;

Code to illustrate the use of charAt() method

package com.TechVidvan.StringDemo;
public class CharacterAtPosition
{
  public static void main(String args[])
  {
           String sentence = "Tech Vidvan";
           char result = sentence.charAt(8);
           System.out.println("At position 8, the character is: " +result);
           System.out.println("At position 1, the character is: " +sentence.charAt(1));
  }
}

Output:

At position 8, the character is: v
At position 1, the character is: e

3. String concat(String string1) method

The method concat() is used for concatenating or adding two strings into a single string. This method appends its String argument to the indicated string argument and returns a new instance of the String class.

Syntax:

string1.concat(string2);

Code to illustrate the use of the concat() method:

package com.TechVidvan.StringDemo;
public class StringConcatenation
{
  public static void main(String args[])
  {
    String string1 = "Tech Vidvan ";
    String string2 = "Java Tutorial";
    string1 = string1.concat(string2);
    System.out.println("Concatenated String is: " +string1);
  }
}

Output:

Concatenated String is: Tech Vidvan Java Tutorial

We can also use the + operator to produce the same result as the concat method:

package com.TechVidvan.StringDemo;
public class StringConcatenation
{
  public static void main(String args[])
  {
    String string1 = "Tech Vidvan ";
    String string2 = "Java Tutorial";
    string1 = string1 + string2;
    System.out.println("Concatenated String is: " +string1);
  }
}

Output:

Concatenated String is: Tech Vidvan Java Tutorial

4. String substring(int beginIndex) method

The substring method with a single argument is used to create new objects or instances of String class from existing instances of String. The method returns the substring from the index which is passed as an argument to the method.

Syntax:

sentence.substring(beginIndex) ;

Code to illustrate the use of the substring(int index) method:

package com.TechVidvan.StringDemo;
public class SubStrings
{
  public static void main(String args[])
  {
    String sentence = "Welcome to TechVidvan Tutorial on Strings";
    String subString = sentence.substring(11);
    System.out.println( "The Substring is: " +subString) ;
  }
}

Output:

The Substring is: TechVidvan Tutorial on Strings

5. String substring(int beginIndex, int endIndex) method

The substring with two arguments method is used to create new objects or instances of String class from existing instances of String. The method returns the new String by using the required index range (including the start index and excluding the end index).

Syntax:

sentence.substring(beginIndex, endIndex) ;

Code to illustrate the use of the substring(beginIndex, endIndex) method:

package com.TechVidvan.StringDemo;
public class SubStrings
{
  public static void main(String args[])
  {
    String sentence = "Welcome to TechVidvan Tutorial on Strings";
    String subString1 = sentence.substring(11, 21);
    String subString2 = sentence.substring(22, 30);
    System.out.println("The Substring within the range is: " + subString1);
    System.out.println("The Substring within the range is: " + subString2);
  }
}

Output:

The Substring within the range is: TechVidvan
The Substring within the range is: Tutorial

6. int compareTo(String string1, String string2) method

When we use the compareTo() method, the method returns an integer which indicates the lexicographic (alphabetical) comparison of the two strings.

The result is negative if the relative alphabetic value of the particular letter of the first string is smaller than that of the second string’s letter on the same location. And it is positive if the first string is lexicographically larger than the second string.

If both strings are identical, then a value zero(0) is returned.

Syntax:

string1.compareTo(string2) ;

Code to illustrate the use of the concat(string1, string2) method:

package com.TechVidvan.StringDemo;
public class CompareStrings
{
  public static void main(String args[])
  {
    String string1 = "Hello World";
    String string2 = "Hello World";
    int result = string1.compareTo(string2);
    System.out.println(result);

    String sentence = "Welcome ";
    result = sentence.compareTo("to TechVidvan Tutorial ");
    System.out.println(result);

    String sentence1 = "This is a ";
    String sentence2 = "Java Tutorial ";
    result = sentence1.compareTo(sentence2);
    System.out.println(result);
  }
}

Output:

0
-29
10

7. String toUpperCase() method

The method toUpperCase() converts all the characters of a given string to uppercase.

Syntax:

sentence.toUpperCase() ;

Code to illustrate the use of the toUpperCase() method:

package com.TechVidvan.StringDemo;
public class CaseConversion
{
  public static void main(String args[])
  {
    String string1 = "Hello World";
    String string2 = "welcome to TechVidvan";
    System.out.println(string1.toUpperCase());
    System.out.println(string2.toUpperCase());
  }
}

Output:

HELLO WORLD
WELCOME TO TECHVIDVAN

8. String toLowerCase() method

The method toLowerCase() converts all the characters of a given string to lowercase.

Syntax:

sentence.toLowerCase() ;

Code to illustrate the use of the toLowerCase() method:

package com.TechVidvan.StringDemo;
public class CaseConversion
{
  public static void main(String args[])
  {
    String string1 = "HELLO WORLD";
    String string2 = "WELCOME TO TECHVIDVAN";
    System.out.println(string1.toLowerCase());
    System.out.println(string2.toLowerCase());
  }
}

Output:

hello world
welcome to techvidvan

9. String trim() method

This method returns the new String after removing whitespaces at both ends. It does not affect whitespaces in the middle of the String.

Syntax:

sentence.trim() ;

Code to illustrate the use of the trim() method:

package com.TechVidvan.StringDemo;
public class TrimString
{
  public static void main(String args[])
  {
    String string1 = " This is a Tutorial on Strings ";
    System.out.println("The original string is:" +string1);
    System.out.println("The trimmed string is:" +string1.trim());
  }
}

Output:

The original string is: This is a Tutorial on Strings
The trimmed string is:This is a Tutorial on Strings

10. String replace(char oldChar, char newChar)

This method replaces each occurrence of the first argument of the string with the second argument and returns the resulting string.

Syntax:

sentence.replace(char1, char2) ;

Code to illustrate the use of the trim() method:

package com.TechVidvan.StringDemo;
public class ReplaceString
{
  public static void main(String args[])
  {
       //Replacing all the 'a' with 'e'
        String string1="TechVidvan is a good tutorial";
       String replaceString=string1.replace('a','e');
            //replaces all occurrences of 'a' to 'e'
             System.out.println("String after replacing characters is: " +replaceString);

  }
}

Output:

String after replacing characters is: TechVidven is e good tutoriel

Summary

Strings play a very important role in Java programming. Java provides a String class to manipulate and perform operations on strings. In this article, we have studied the String class which belongs to java.lang package.

We also covered the essential methods useful while dealing with Strings along with their syntax and sample codes. This article will help you in writing Java programs related to Strings.

Thank you for reading our article. Do share our article on Social Media.

Happy Learning 🙂

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.