String Class in Java | Methods, Example

In an application or a program, it is common to work with the sequence of text character (e.g., for user interactions or data processing).

To support character strings, Java programming language provides a string class. This string class helps to manage text strings effortlessly in the java program.

String class in Java is used to represent character strings. That is, it is used to store multiple characters.

For example, strings such as “12346” and “hello world” are really instances of this class. In Java world, String instances/objects are usually just called “strings”.

As we recall, all strings are stored in heap space when we create string using constructors defined in the java.lang.String class.

When we create a string directly in double quote without using constructor, that string is stored in a special area of heap space known as “string constant pool”.

String Class Syntax and Hierarchy


The general syntax to declare a string class in java is as follows:

public final class String
    extends Object
        implements Serializable, Comparable<String>, CharSequence

Java String class inherits from java.lang.Object class. So, in addition to the functionality provided by String class, string can also use all the functionality provided by the Object class and can override them.

This class also implements three interfaces such as CharSequence, Comparable, and Serializable. String in Java is final class, which means it cannot be extended.

String Class Constructor


String class provides several constructors in java but for the purpose of exam, we only need to be aware of the following constructors.

1. String(): This constructor creates an empty String.

2. String(byte[ ] bytes): This constructor constructs a new string object by decoding (or converting) the specified array of bytes using the platform’s default charset.

3. String(byte[ ] bytes, Charset charset): It creates a new string object by decoding the specified array of bytes using the specified charset.

4. String(byte[ ] bytes, int offset, int length): This form of constructor creates a new string object by decoding the specified subarray of bytes using the platform’s default charset.


5. String(byte[ ] bytes, int offset, int length, Charset charset): This form of constructor creates a new string object by decoding the specified subarray of bytes using the specified charset.

6. String(byte[ ] bytes, int offset, int length, String charsetName): This constructor constructs a new string object by decoding the specified subarray of bytes using the specified charset.

7. String(byte[ ] bytes, String charsetName): It creates a new string object by decoding the specified array of bytes using the specified charset.

8. String(char[ ] value): This form of constructor allocates a new String so that it represents the sequence of characters currently contained in the character array argument.


9. String(char[ ] value, int offset, int count): This form of constructor allocates a new String that contains characters from a subarray of the character array argument.

10. String(int[ ] codePoints, int offset, int count): This constructor allocates a new string object that contains characters from a subarray of the Unicode code point array argument.

11. String(String value): It initializes a newly created string object with the same sequence of characters as the argument string. In other words, the newly created string object is a copy of the argument string.


12. String(StringBuffer buffer): It allocates a new string object that contains the sequence of characters currently contained in the string buffer argument.

13. String(StringBuilder builder): This constructor allocates a new string object that contains the sequence of characters currently contained in the string builder argument.

Java String Class Methods


The java.lang.String class provides various useful methods to perform operations like:

  • convert the string into a character array
  • Convert numbers into strings
  • search strings
  • create substrings
  • get a string length, and much more.

The most important and commonly used methods in the String class are as follows:

1. isEmpty(): This method is used to check that the string is empty or not. If the length of the string is 0 i.e. the string is empty it will return true otherwise false.

The general syntax for isEmpty() method with an example is as follows:

Syntax:
     public boolean isEmpty() // Return type of this method is boolean.
For example:
    String s=" ";
     s.isEmpty(); // It will return true because string is empty.

Let’s take a simple example program based on isEmpty() method.

Program source code 1:

public class IsEmptyTest {
public static void main(String[] args) 
{
  String str = ""; // Empty string.
  boolean isEmpty1 = str.isEmpty();
  System.out.println("Is String empty: " +isEmpty1);

  String str2 = " ";
  boolean isEmpty2 = str2.isEmpty();
  System.out.println("Is String empty: " +isEmpty2);
 }
}
Output:
      Is String empty: true
      Is String empty: false

2. length(): The number of characters in a string is called length of a string. To get this value, call length() method.

The length() method returns length or number of characters of a string. It counts all characters, numbers, and symbols enclosed in ” “. The return type of this method is an integer value.

The general syntax of length() method with an example is given below:

Syntax: 
      public int length()
For example:
  String s = "Hello";
   s.length(); // 5 returns the number of charaters in the string s.

Note: s.length; Here length is a variable that is applicable for an array but not for string. So, you do not confuse between s.length and s.length().


Program source code 2:

public class LengthTest {
public static void main(String[] args) 
{
   String str = ""; // Empty string.
// Find the length of string.
    int length = str.length();
    System.out.println("Length of string: " +length);

    String str2 = "I like Scientech Easy";
    int length2 = str2.length();
    System.out.println("Length of string: " +length2);

   char arr[] = {'S','c','i','e','n','t','e','c','h'};
   String str3 = new String(arr);
   System.out.println("Length of characters: " +str3.length());
 }
}
Output:
       Length of string: 0
       Length of string: 21
       Length of characters: 9

3. replace(char old, char new): This method is introduced in JDK 1.5. It replaces all the old char or CharSequence to new char or CharSequence. It has the following general syntax:

Syntax:
      String replace(char old, char new)

For example:
   String s1="Kava";
    s1.replace('K', 'J'); // The returned string will be "Java".

Let’s take an example program based on this method.

Program source code 3:

public class ReplaceExample {
public static void main(String[] args)
{
  String str = "Programming";
  String s1 = str.replace('m', 'n');
  System.out.println("str.replace('m', 'n'): " +s1);
 } 
}
Output:
      str.replace('m', 'n'): Progranning

4. toUpperCase(): The toUpperCase() method converts all the lowercase letters of a string into upper case and returns that upper-cased string.

public String toUpperCase()

To understand more detail with example programs and memory concepts, go to this tutorial: Java String toUpperCase() method.

5. toLowerCase(): This method converts all the uppercase letters of a string into lower case and returns that lower-cased string.

public String toLowerCase()

To understand in more detail with example programs, go to this tutorial: Java String toLowerCase() method.

Program source code 4:

public class CaseExample {
public static void main(String[] args)
{
  String str = "TECHNOLOGY";
  System.out.println("str.toLowerCase(): " +str.toLowerCase());
  String s = "programming";
  System.out.println("s.toUpperCase(): " +s.toUpperCase());
  } 
}
Output:
     str.toLowerCase(): technology
     s.toUpperCase(): PROGRAMMING

6. charAt(int index): The charAt() method returns the character located at specified index. It accepts an integer value that represents an index number. The index number starts at 0 and goes to (n-1) where n is the length of the string.

If the specified index number is greater than or equal to this string length or a negative number, it will return StringIndexOutOfBoundsException. The syntax of this method is given below:

Syntax:
      public char charAt(int index)

For example, suppose we call this method as s.charAt(4); then it will give the 4th character in the string s.

To get more example programs based on this method, go to this tutorial: How to get character from string in Java


7. trim(): This trim() method removes spaces from the beginning and ending from a string.

For example, suppose a string is written as ”  Scientech Easy  “, the spaces before “Scientech” and after “Easy” is unnecessary. So, it can be removed by calling trim() method. It has the following general form.

Syntax:
     public String trim()

This method does not remove spaces from the middle of a string. For example, the space between “Scientech” and “Easy” cannot be removed using the trim() method.

Let’s create a program where we will remove space from beginning and end in a string.

Program source code 5:

public class RemovingSpace {
public static void main(String[] args)
{
   String str = new String(" Scientech Easy ");
   System.out.println("Original string: " +str);
// Removing space from beginning and end.
    String trimElement = str.trim();
    System.out.println("After removing space, String: " +trimElement);
  } 
}
Output:
    Original string:  Scientech Easy 
    After removing space, String: Scientech Easy

8. substring(int startIndex): This method returns a new string that is a substring of this string. Here, startIndex represents the index at which substring begins with a character.

The substring starts at startIndex and executes until the end of the string. It has the following general form.

Syntax:
      public String substring(int startIndex)

For example,
     String s = "India";
         s.substring(3);

Here, startIndex is 3. So, it will return characters starting 3rd character till the end of s.

9. substring(int startIndex, int endIndex): This method returns a new string of all the characters from starting index up to ending index but not including, the ending index. For example,

String s="India";
      s.substring(1,3);

It will return the characters of s starting from 1st to 2nd positions. To practice more example programs, go to this tutorial: Substring in Java


10. contains(CharSequence s): This method returns true if this string contains the specified sequence of char value. It has the following general form:

boolean contains(CharSequence s)

Let’s take an example program base don this method.

Program source code 6:

public class ContainsExample {
public static void main(String[] args)
{
  String str = new String("I love Java");
  boolean str2 = str.contains("Love");
  boolean str3 = str.contains("Java");
   System.out.println("str2: " +str2);
   System.out.println("str3: " +str3);
  } 
}
Output:
     str2: false
     str3: true

11. compareTo(String str): This method compares two strings and to know which is bigger or smaller. It can be used as: s1.compareTo(s2). Here, s1 and s2 are string compared.

If s1 and s2 strings are equal, this method provides 0. If s1 is greater than s2, it returns positive number. If s1 is less than s2, it returns a negative number. It has the following general form:

int compareTo(String str)

12. compareToIgnoreCase(String str): It is same as compareTo() method. This method does not take the case of strings into consideration. This means “LOVE” and “love” will be the same for this method.

The general form of this method is as follows:

int compareToIgnoreCase(String str)

Let’s create a simple program in which we will compare two strings using these two methods.

Program source code 7:

public class StringCompare {
public static void main(String[] args)
{
 String str = "Love";
 String s = "love";
 int x = str.compareTo(s);
 System.out.println("str.compareTo(s): " +x);
 int y = str.compareToIgnoreCase(s);
 System.out.println("str.compareToIgnoreCase(s): " +y);
  } 
}
Output:
    str.compareTo(s): -32
    str.compareToIgnoreCase(s): 0

13. equals(String str): This method returns true if two strings are equal or same. It is case sensitive and can be used as s1.equals(s2);. The general form of this method is as follows:

boolean equals(String str)

14. equalsIgnoreCase(String s): This method is the same as equals() method, but it does case-insensitive comparison. The general syntax is as follows:

boolean equalsIgnoreCase(String s)

Program source code 8:

public class StringCompare {
public static void main(String[] args)
{
 String str = "Love";
 String s = "love";
 boolean x = str.equals(s);
 System.out.println("str.equals(s): " +x);
 boolean y = str.equalsIgnoreCase(s);
 System.out.println("str.equalsIgnoreCase(s): " +y);
  } 
}
Output:
      str.equals(s): false
      str.equalsIgnoreCase(s): true

15. startsWith(String s): This method returns true if a string starts with the specified substring s. To invoke this method, use this format: s1.startsWith(s2);. If s1 starts with s2, it returns true, otherwise false. This method is case sensitive. The general form is like this:

boolean startsWith(String s)

16. endsWith(String s): This method returns true if a string ends with the specified substring s, otherwise, it returns false. This method is also case-sensitive. The general form of this method is like this:

boolean endsWith(String s)

Let’s take an example program based on the above both methods.

Program source code 9:

public class StartsEndsExample {
public static void main(String[] args)
{
  String str = "Technology";
  boolean x = str.startsWith("c");
  System.out.println("str.startsWith(): " +x);
  boolean y = str.endsWith("y");
  System.out.println("str.endsWith(): " +y);
  } 
}
Output:
      str.startsWith(): false
      str.endsWith(): true

19. indexOf(String str): This method is used to get index of the first occurrence of specified substring in the main string. It returns integer value as index. The general syntax is like this:

public int indexOf(String str)

20. lastIndexOf(String str): This method is similar to the preceding method, but returns the last occurrence of substring str in the main string. If str is not found, it returns false.

public int lastIndexOf(String str)

Let’s create a program in which we will get the index value of the first and last occurrences of the given string.

Program source code 10:

public class IndexExample {
public static void main(String[] args)
{
  String str = "Programming";
  int x = str.indexOf("m");
  System.out.println("str.indexOf(): " +x);
  System.out.println("str.lastIndexOf(): " +str.lastIndexOf("g"));
  } 
}
Output:
      str.indexOf(): 6
      str.lastIndexOf(): 10

21. String[ ] split(delimiter): This method is used to break a string into pieces at the place represented by the delimiter. It returns the resultant pieces in the form string type array.

For example, suppose the delimiter is comma, the string is split (or cut) pieces whereever ‘,’ if found. The general syntax to define this method is as follows:

public String[ ] split(delimiter)

Let’s create a program for splitting a string into pieces whenever a space is found.

Program source code 11:

public class SplitExample {
public static void main(String[] args)
{
 String str = "I love Java Technology";
 String[ ] s;
       s = str.split(" ");
  int length = str.length();
  for(int i = 0;  i < length; i++) {
	  System.out.println(s[i]);
    }
 } 
}
Output:
       I
       love
      Java
      Technology

Hope this tutorial has covered almost all the important points related to String class in Java and its methods with various example programs. I hope that you will have understood and practiced all programs.
Thanks for reading!!!
Next ⇒ String Constructor in Java⇐ Prev Next ⇒

Leave a Comment