Strings in Java

Video Tutorial
FREE
Strings Introduction thumbnail
This video belongs to
Java Course - Mastering the Fundamentals
12 modules
Certificate
Topics Covered

Overview

In Java, We have a String class for creating and manipulating strings.

The String class is one of the classes which implement this interface. Hence, string is basically an object that represents a sequence of char values..

We have different String methods such as concat(), length(), compareTo(), equals(), etc. to handle various string operations.

What is a String in Java?

There exists a primitive data type char in Java which is used to declare character-type variables. It represents or stores a single character. But what if we need to store any name or a sequence of characters?

There can be two ways(or methods) of doing this:

Using char[] array in Java

Output:

Using String class in Java

Output:

Using Strings in Java

As you can see in picture above, String is an array of characters. Let us see how to create string objects in Java.

How to Create a String Object?

String object can be created using two ways:

  1. Using String Literal.
  2. Using new keyword.

String Literal and String Constant Pool

A literal, in computer science, is a notation used for representing a value. Java String literal can be created and represented using the double-quotes. All of the content/characters can be added in between the double quotes.

For Example:

In the above-given example, we have declared a string variable called scalerAcad and initialized it with the string value "Scaler Academy".

Now we will see the memory management of Strings in Java. The Strings in Java are stored in a special place in heap called "String Constant Pool" or "String Pool".

String Constant Pool

The string constant pool in Java is a storage area in the heap memory that stores string literals. When a string is created, the JVM checks if the same value exists in the string pool. If it does, the reference to that existing object is returned. Otherwise, a new string object is created and added to the string pool, and its reference is returned.

Image for Reference: String constant pool

Why is only one string object created in the string constant pool when two strings are created using the string literal method in the above example?

  • When str1 is initialized, the JVM checks the string constant pool for the string value "Scaler". If it's not present, a new string object is created and stored in the pool.
  • When str2 is initialized, the JVM checks the string constant pool for the string value "Scaler". Since it's already present (due to str1), a new string value is not created. Instead, str2 points to the existing value.

By New Keyword

Strings can indeed be created using the new keyword in Java. When a string is created with new, a new object of the String class is created in the heap memory, outside the string constant pool.

Unlike string literals, these objects are allocated separate memory space in the heap, regardless of whether the same value already exists in the heap or not.

Syntax:

Example: Creating Java Strings using the new keyword

Image for Reference: Creating Java Strings using the new keyword

Example of Strings in Java

Now we are going to see some more examples of string in Java.

In the above-given examples, val1 is created using the string literal, val2 is created using the new keyword and val3 is created by concatenating/joining val1 and val2.

Methods of Java Strings

1. int length() Method

The length() method of string in Java is used to get the length of the string. In some cases, programs act according to the length of the string, and hence this method comes in very handy at that time.

Syntax:

Example:

Output:

2. char charAt(int index) Method

The charAt() method of string in Java accepts an index number as an argument and returns the character at the given index number.

The indexing is from 0 to length-1, where length is the length of the string. In case the passed index number is not present in the string(if it's equal to or greater than the length of the string or if it is a negative number), StringIndexOutOfBoundsException is thrown.

Syntax:

Example :

Output:

Exception Example:

Output:

Explanation: In the above-given example, when we passed 14 as an argument index number, we got StringIndexOutOfBoundsException. It is because the length of the string = 14, hence highest index in the string is 13.

3. String concat(String string1) Method

Details: What if we want to concat(or connect) two strings?

We have a method for that too! The concat() method of string in Java is used for concatenating two strings.

Syntax:

Example:

Output:

4. String substring(int beginIndex, int endIndex[optional]) method

Details: The substring() method in Java returns a specified part of a string. It takes two parameters: the starting index (inclusive) and the ending index (exclusive). The substring will include characters starting from the beginIndex up to endIndex - 1.

If we do not provide the endIndex, it is assumed to be the length of the string.

Syntax:

Example:

Output:

5. String equals(String anotherString) method

The equals() method of string in Java is used to verify if both the strings are equal or not. The equals method accepts another string as an argument and then checks for the equality of both the strings. If both the strings are equal, true is returned else false is returned.

Syntax:

Example:

Output:

6. String contains(String substring) Method

The contains() method in Java is used to check if a string contains a specified substring. It returns true if the substring is found and false otherwise.

Syntax:

Example:

Output:

7. String join()

Details: The join() method of string in Java as the name suggests is used to join a group of strings using the joiner between them. The joiner variable can be any character, string or a sequence of characters.

Syntax:

Example:

Output:

8. int compareTo(String string1, String string2) Method

Details: The compareTo() method of string in Java compares the given strings in the order of occurrence in the dictionary. The comparison is solely based on the Unicode value of the characters of the strings.

Syntax:

Example:

Output:

9. String toUpperCase() Method

Details: The toUpperCase() method of string in Java is used to convert the lowercase characters of the string to the uppercase(or capital) characters.

Syntax:

Example:

Output:

It should be noted that there's no change in the original string str.

10. String toLowerCase() Method

Details: The toLowerCase() method of string in Java is used to convert all the characters of the string to the lowercase(or small) characters.

Syntax:

Example:

Output:

Example:

Output:

11. String trim() Method

Details: The trim() method of string in Java is used to trim (or remove) the extra white spaces from the specified string from both the ends.

Syntax:

Example:

Output:

Explanation: In the above example, we have used the trim() method to trim the extra white spaces of string str at the ends only.

Please note that it does not remove extra whitespaces if they are present between the text and not at the ends. Use this Online Compiler to compile your Java code.

12. String replace(char oldChar, char newChar)

Details: The replace() method of string in Java as the name suggests is used to replace all the specified character of the string with another character.

Syntax:

Example:

Output:

Concatenating Strings

String concatenation in Java involves combining two strings using the + operator or the concat() method. It is important to note that the original string remains unchanged unless explicitly modified.

Syntax:

Example-1:

Output:

Creating Format Strings

Details: The format() method is used to format the string as per the passed argument. This method accepts two arguments: format string and argument(s), then returns the formatted string.

Syntax:

Example:

Output:

Explanation: In the above example, we have used the %s format specifier which is reserved for strings, Henced India got printed in place of %s. Similarly, there are format specifiers for int(%d), float(%f), etc. which can be used for formatting of these data type values.

Escape Character () in Java Strings

Escape character is the character with a backslash \ before it.

Example:

Output:

Explanation:

To include double quotes within a Java string, we use the escape character \. Placing a backslash before the double quotes indicates that they should be treated as part of the string, avoiding errors.

Example-1

Output:

Some more examples of escape character for tab, backslash, and a new line. Example-2

Output:

Java Strings: Mutable or Immutable

In Java, strings are immutable, meaning their values cannot be changed once initialized. This is because a single string object in the String constant pool can have multiple references. Modifying the value of one reference could affect other strings or reference variables, leading to conflicts. To prevent these conflicts, string objects are made immutable in Java.

The concept of the String Constant Pool is closely tied to string immutability in Java.

Although it may seem like string values can be changed in previous sections of this article, the actual string value remains unchanged.

Let us understand with the help of an example:

In Java, strings are immutable. When we concatenate a string like " to all" with str, a new string value is created. str then points to this newly created value, while the original value remains unchanged. This behavior demonstrates the immutability of strings in Java.

Conclusion

  • Strings in Java are objects that represent a sequence of characters.
  • String literals are stored in the String pool, a special area in the heap.
  • Strings can be created using string literals or the new keyword.
  • The new keyword allocates memory outside the string pool.
  • Various string methods exist to work with strings in Java.
  • Concatenation can be done using the + operator or concat() method.
  • String formatting is possible with the format() method.
  • The escape character \ can be used to handle special characters in strings.
  • Strings in Java are immutable, meaning their values cannot be changed after initialization.

Read more