Java String Tutorial

What is a String in Java?

A String in Java is an object that represents an array of characters. It is an immutable object. Whenever a change to a String is made, an entirely new String gets created.

There are two ways to create a String:

  1. Using String literal
  2. With a new keyword


1. String literal

When creating a new String, we assign it a value within double quotes:

 String str = "Hello";


2. With a new keyword

To create a String, we can instantiate it, just like any other class in Java:

 String str = new String("Hello");


What is the difference?

First, let’s understand what a String pool is.

What is a String pool in Java?

String pool is a storage area in the Java heap memory part.

Since creating a new String is costly in both the cases of time and memory, the JVM keeps a pool of strings.

A String pool allows JVM to save memory by preserving immutable strings in a pool so that the application can reuse instances of common strings instead of creating multiple instances.

Take a look at this picture:

java string pool

Here we can conclude the following:

When we first create a String with a String literal, that value goes to the String pool, and each time we use the same literal to create other strings, the existing will be reused.

This saves memory and improves performance because new String objects are not created, but existing String literals from the String pool are used.

When using the new keyword, new objects are created in the Java Heap memory every time we create a String.

Let’s see one example:

class Test {

  public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = "Hello";
    String str3 = new String("Hello");
       
    System.out.println(str1 == str2);
    System.out.println(str1 == str3);
  }
}
Output: true false
 
Here:
  • We create str1 by assigning it a String literal. Then, that value goes to the String pool.
  • Then, we create a new String str2 and assign it the same literal. The new object will not be created. The existing String literal from the String pool will be used.
  • After that, we create a new String str3 by instantiating it with the keyword new, a new object is created, and it will be outside the String pool part.
  • We compare str1 and str2, and we get true because both strings point to the same object.
  • Then, we compare str1 and str3, and we get false because they are two different objects.

To answer the above question:

The difference between creating a String with a literal and a new keyword is that if we use a String literal, the JVM will use a String pool and save a lot of memory and increase performance, while with the new keyword it will create a new object in Java heap memory each time, which is a significantly expensive operation.

String in Java is a sequence of char values

A String is actually an array of characters. Note the following example:

class Test {
  
  public static void main(String[] args) {
    char[] chars = {'a', 'l', 'e', 'g', 'r', 'u'};
    String str = new String(chars);
        
    // above is equivalent to:
    String str1 = "alegru";
  }
}


Java String class methods

The java.lang.String class provides many useful methods for dealing with a sequence of char values:

Method Description
char charAt(int index) Returns the character at the specified index.
int compareTo(Object o) Compares this String to another Object.
int compareTo(String anotherString) Compares two strings lexicographically.
int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array.
int hashCode() Returns a hash code for this string.
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
String intern() Returns a canonical representation for the string object.
int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character.
int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
String substring(int beginIndex) Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.
char[] toCharArray() Converts this string to a new character array.
String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale.
String toString() This object (which is already a string!) is itself returned.
String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale.
String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale.
String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(primitive data type x) Returns the string representation of the passed data type argument.
String concat(String str) Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
static String copyValueOf(char[] data) Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count) Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
boolean equals(Object anObject) Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations.
byte[] getBytes() Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
byte[] getBytes(String charsetName) Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
int length() Returns the length of this string.
boolean matches(String regex) Tells whether or not this string matches the given regular expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal.
String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replaceAll(String regex, String replacement Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement.
String[] split(String regex) Splits this string around matches of the given regular expression.
String[] split(String regex, int limit) Splits this string around matches of the given regular expression.
boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix beginning a specified index.
CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence that is a subsequence of this sequence.


That’s it!

Leave a Reply

Your email address will not be published.