Class relations: + java.lang.Object + - java.lang.String

Implemented interfaces: Serializable, CharSequence, Comparable<String>

Thread safe: True


In Java, String is not a primitive data type. String is an object type that implemented as an array of characters.

char[] ch = {'S', 't', 'r', 'i', 'n', 'g'};
String s = new String(ch);
System.out.println(s);
String

In Java, you can create string object using string literal or the new key word.

String s = "Hello";
String st = new String("Hello");

String pool

In Java, the string pool is a special area in the Java heap where string literals are stored. It is also known as the string intern pool or string constant pool. When you create a string literal, the JVM checks if the string literal already exists in the string pool. If a string literal is already present in the pool, a reference to that string literal is returned. If the string literal does not exist in the pool, a new string object is created and added to the string pool. Because of the string pool, identical string literals are stored only once, which conserves memory.

String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
true
false

When s1 is initialised, the JVM checks if the string literal “Hello” exists in the string pool, since it does not exist, a new string literal “Hello” is added to the pool, and s1 is referenced to this string literal in the pool. When s2 is initialised, the JVM finds the string literal “Hello” is already exists in the pool, the s2 is reference to the same literal as s1. In the first print statement, the references of both s1 and s2 are compared, since they both reference to the same string instance in the pool, the expression evaluates to true. When initialising s3, the new keyword is used, this keyword always creates a new object, a new string object is created on the heap, separated from the string pool, which points s3 to a different memory location. When compare the reference address of s1 and s3, since s3 has a different memory address, the expression evaluates to false.

String is immutable

String in Java is immutable which means once a string is created it cannot be changed. Any operating to modify a string is actually creating a new string object.

This line of code creates a name variable and assigned it with the value “John”.

String name = "John"

This is how it works in the memory (arrow is a reference pointer): The name variable is pointed to the “John” instance in the string pool. Now we assign the value “Sally” to this name variable.

name = "Sally";

Java doesn’t modify the string object “John”, but rather, it creates a brand new string object in the string pool with value “Sally”, and the name reference is redirected to point at the new string object. The “John” is dereferenced and name is pointing to the new string object “Sally”.

Since String is immutable, it is inherently thread safe.

String methods

MethodDescriptionRef
char charAt(int index)It returns char value for the particular index
int length()It returns string length
static String format(
String substring(int beginIndex)It returns a substring for given begin index
boolean contains(CharSequence chars)It returns true or false after matching the sequence of char value
static String join(CharSequence delimiter, CharSequence... elements)It returns a joined string
boolean equals(String another)It compares calling string and parameter string based on their content
boolean equalsIgnoreCase(String another)It compares calling string and another string. It doesn’t check case
String replace(char old, char new)It replaces all occurrences of the specified char value
String replace(CharSequence old, CharSequence new)It replaces all occurrences of the specified CharSequence.
String[] split(String regx)It returns a split string matching regex
int indexOf(int ch)It returns the specified char value index, can take Unicode value
String toLowerCase()It returns a string in lowercase
String toUpperCase()It returns a string in uppercase
String trim()It removes beginning and ending spaces of this string
static String valueOf(Object o)It converts a given type into string, can take primitive types

substring()

The substring() method has two variants, it returns a new string that is substring of the calling string. Any space is counted as an index.

  • String substring(int beginIndex)
    • Takes a begin index, the begin index is inclusive and starts from 0.
  • String substring(int beginIndex, int endIndex)
    • Takes a begin index and an end index, the end index is exclusive and starts from 1.
String s = "Hello Word";
System.out.println(s.substring(1, 3));
el

join()

The join method in string class is a static method used to concatenate multiple strings, or elements of an Iterable of CharSequence object (e.g. StringBuilder objects, list of strings, set of strings) into a single string, with a specified delimiter separating each element.

  • String join(CharSequence delimiter, CharSequence... elements)
    • Join with CharSequence elements, the delimiter separates each element in the resulting string.
  • String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
    • Join with an Iterable of CharSequence objects, with delimiter separates each object.

Join with CharSequence elements

String joinString = String.join("-","This","is","joined","string");  
System.out.println(joinString);
This-is-joined-string

Join with Iterable CharSequence objects

List<String> wordsList = Arrays.asList("dog", "cat", "rabbit");  
String resultList = String.join("-", wordsList);  
System.out.println(resultList);
dog-cat-rabbit

split()

This method splits a string into substrings based on a regular expression (regex), there are two method signatures.

  • String[] split(String regex)
    • Returns an array of strings computed by splitting the string around matches of the given regex.
  • split(String regex, int limit)
    • Takes an additional limit parameter that controls the number of times the pattern is applied and the length of the resulting array.

Split with regular expression

String str = "apple+banana+cherry";  
// + has sepcial meaning in regex, use \\ to escape the inherent meaning
String[] result = str.split("\\+");  
System.out.println(Arrays.toString(result));
[apple, banana, cherry]

Split with regular expression and limit

  • When limit is positive, the pattern is applied at most limit - 1 times, the last element will contain the remaining part of the string.
  • When limit is zero, the pattern is applied as many times as possible. Trailing empty strings are discarded.
  • When limit is negative, the pattern is applied as many times as possible. The resulting array can have any length, and trailing empty strings are not discarded.
String str = "apple,banana,cherry";
String[] result = str.split(",", 2);
for (String s : result) {
    System.out.println(s);
}
apple
banana,cherry

Back to parent page: Java Standard Edition (Java SE) and Java Programming

Web_and_App_DevelopmentProgramming_LanguagesJavaStringString_Pool

Reference: