April 16, 2022

Java String Class With Method Examples

In this tutorial we’ll learn about String in Java which is one of the most important and extensively used class in Java.

Java String

String in Java is a sequence of characters and it is represented by String class residing in java.lang Package.

Whenever you create a String in Java it is created as an object of String class. String class provides many constructors and methods to create and manipulate strings, in this post and in successive posts we'll see application of some of the most used String methods.

Creating String in Java

Since every string in Java is an instance of String class so a new String can of course be created using new operator. Apart from that String can also be created by assigning a string literal to a String instance.

So, there are two ways to create a String-

  1. Using String literal
  2. Using new keyword

Creating Java String using string literal

The most direct way to create a string is to assign String literal to an instance of String, for example

String str = "Hello";

In this case, "Hello" is a string literal; a series of characters that is enclosed in double quotes. Whenever Java compiler encounters a string literal in your code, the compiler creates a String object with its value.

One interesting point about creating string using string literal is that for string literals JVM may create only single instance in memory. What that means is, if there are more than one string literals having the same value they all point to the same String reference in memory.

For that Java uses a structure called constant String pool. When a String is created using string literal JVM looks in this string pool to find if a String with the same value already exists in the pool. If such a String already exists then the created String also refers to the same String otherwise a new String object is created and stored in the String pool.

For example if two Strings are created as follows-

String str1 = “Hello”;
String str2 = “Hello”;

How these values are stored in the String pool is explained using the following image.

String in Java

You can also verify it using a Java program. In the example two Strings are created using string literals and then their references are compared using equality '==' operator.

public class StringLiteral {
  public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = "Hello";
    // checking if memory reference is same
    if(str1 == str2){
      System.out.println("str1 and str2 are pointing to same memory reference");
    }else{
      System.out.println("str1 and str2 are not pointing to same memory reference");
    }
  }
}
Output
str1 and str2 are pointing to same memory reference

To know more about constant String pool in Java check this post- Constant String Pool in Java

Creating String using new keyword

You can also create String instance using new operator. In String class there are thirteen constructors that allow you to provide the initial value of the string using different sources like char array, byte array, StringBuffer, StringBuilder etc.

String str = new String(); // empty character sequence

String str1 = new String("Hello");

char[] helloArray = { 'H', 'e', 'l', 'l', 'o'};
String str2 = new String(helloArray);

Note that when String is created using new operator even if two Strings have same values they are stored as separate objects in memory, instance is not shared as in the case of String literal.

public class StringLiteral {
  public static void main(String[] args) {
    String str1 = new String("Hello");
    String str2 =  new String("Hello");
    // checking if memory reference is same
    if(str1 == str2){
      System.out.println("str1 and str2 are pointing to same memory reference");
    }else{
      System.out.println("str1 and str2 are not pointing to same memory reference");
    }
  }
}
Output
str1 and str2 are not pointing to same memory reference

As you can see even if the value is same for two String objects created using new operator now the reference is not shared.

String concatenation using overloaded operators

Though String class has a concat() method for concatenating String but the Strings are more commonly concatenated using + or += operator.

These two operators + and += are overloaded in Java to work with Strings. For example-

String str = "Hello" + " " + "World";
System.out.println(str); 
// Output -- Hello World
String str1 = "Hello";
String str2 = "World";
str1 += " " + str2;
System.out.println(str1);
// prints Hello World

Point to note here is that String class is immutable which means once a String object is created it cannot be changed. When you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains the result of the operation.

To know more about why String is immutable in Java check this post- Why String is Immutable in Java

In the case string is modified frequently you should consider using StringBuffer or StringBuilder classes which are mutable variant of the String class.

Creating Formatted Strings

In String class there is a static method format() that returns a formatted String. Unlike printf that just prints using format() method of String class you get a String that can be reused.

public class StringLiteral {
  public static void main(String[] args) {
    float rate = 5.5f;
    int duration = 3;
    double amount = 12000;
    String name = "Jack";
    String str = String.format("Amount of %6.2f " +
                "deposited at rate %2.1f " +
                "for the duration of %d years " + 
                "by %s ",
                amount, rate, duration, name);
    
    System.out.println("Formatted String- " + str);	
  }
}
Output
Formatted String- Amount of 12000.00 deposited at rate 5.5 for the duration of 3 years by Jack 

Important points about String in Java

  1. All the strings you create are instances of String class in Java.
  2. String instance can be created using String literal as well as using new operator.
  3. Whenever Java compiler encounters a string literal in your code, the compiler creates a String object with its value.
  4. In case of String literals, String object is stored in String pool. If there are more than one String literal having the same value they point to the same String reference in the string pool.
  5. When String instance is created using new operator separate objects are created even if the value is same.
  6. String concatenation can be done using "+" operator which is overloaded for String. Since strings are objects of String class comparing two strings using equality operator (==) compares their memory references. To compare content of two strings .equals() or .equalsIgnoreCase() methods should be used.
  7. String class in Java is immutable, once a String is constructed content of that string cannot be modified.
  8. If any String modification method like concatenation is used then a new String is created and returned that contains the result of the operation.
  9. String class is defined as final in Java, which means String class can’t be extended.

Java String class methods

Here is a list of the methods in the String class along with the functionality where these methods can be used.

  1. Length of the String- To get the length of a String you can use length() method of the String class. See example in this post- Java String length() Method With Examples
  2. Compare two Strings- To compare two Strings in Java you can use equals(), equalsIgnoreCase(), compareTo(), compareToIgnoreCase() methods of the String class. For comparing region of one String with the specified region of another String you can use regionMatches() method. See example in this post- Compare Two Strings in Java – equals, compareTo() methods
  3. Search String in another string- To search for a substring in a String you can use indexOf(), lastIndexOf(), contains() methods. See example in this post- Search String in Another String in Java – indexOf, lastIndexOf, contains methods
  4. Getting substring of a String- To get a part of the original String you can use substring() method of the Java String class. See example in this post- Java String – substring() Method Example
  5. Getting specific character from a String- To get specific character of the String by index you can use charAt() method of the String class in Java. See example in this post- Java String charAt() Method
  6. Removing spaces from a String- To remove leading and trailing spaces, remove spaces in between words you can use trim(), strip() and replaceAll() methods. See example in this post- Remove Spaces From a String in Java - trim(), strip()
  7. Changing case of String- Changing case of the String to lower case or uppercase can be done using toLowerCase() and toUpperCase() methods. See example in this post- Java String toLowerCase() And toUpperCase() Methods
  8. Check if String is null, empty or having only whitespaces- That can be done using isEmpty() or isBlank() methods. See example in this post- Check if a String is Null or Empty in Java
  9. intern() method- Returns a canonical representation for the string object. Read more in this post- Java String intern() Method
  10. split() method- Used to split a String around matches of the given regular expression. Read more in this post- Java String split() Method
  11. join() method- Used to join together passed strings using the specified delimiter. Read more in this post- Java String join() Method

That's all for the topic Java String Class With Method Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment