Java

Strings in Java: Explained

A string is an immutable object representing a sequence of characters in Java. The immutable property does not allow you to modify a single character of the string, you have to delete the whole string or make a new one. This article provides a detailed guide on Java strings that would result in the following learning outcomes:

  • possible ways to create a String object in Java
  • methods supported by the String class in Java
  • using strings in Java

How to create a string

The string can be created either by a string literal or by using a new operator of Java. This section guides you to create a string using both methods.

Method 1: Using a string literal

A string literal is the most common practice being followed o create a new string in Java. The first syntax provided below refers to creating a string using a string literal:

String s="<value>"

The instances in the above syntax are:

  • String is the keyword used to create string literals
  • s is the string object’s name
  • the <value> is the sequence of characters

Whenever the string object is created using the string literal method, JVM matches the string(being created) in the existing list of strings (from string constant pool). If the string already exists, this method will not create a new string, it will refer to the already stored string.

Method 2: Using the new operator

The following syntax can be followed to create a string in Java using the new keyword.

String = new String("<value>")

The new operator always creates a new object rather than referring to the already stored string. Thus, it is recommended to create a string using the string literal as this method optimizes the memory as well.

Example
This example demonstrates the way to create a string object using both methods stated here. The following lines of code in Java is practiced doing so:

package newpack;
public class Strings {
public static void main(String[]args) {
   
    //initializing string using String literal  
    String s="linuxhint";

    //initializing the string using "new" operator
    String s1 = new String("Happy coding using Java!");
   
    System.out.println(s);
    System.out.println(s1);
    }
}

Firstly, a string object is created using the string literal and then the new operator is used to create a string. Lastly, the sequence of characters stored in each string object is printed. The following image shows the output of the code:

Methods supported by the Java string class

The Java string class supports various methods that assist in getting information about any string literal.

Let’s dig into them one by one,

length(): This method is mostly used in strings and it returns the number of characters of a string.

Syntax

string.length();

charAt(): This string class method returns the character stored at a specific position(index) of strings.

Syntax

string.charAt(index);

In the above syntax, string is the name of a string object and index shows the position(integer) of the character you want to retrieve

compareTo(): This method compares two strings and returns the number of unmatched characters.

Syntax

string1.compareTo(string2);

The string1 and string2 refer to the strings that you want to compare.

compareToIgnoreCase(): This method matches the string without case-sensitive issues and returns the number of unmatched characters.

Syntax

string1.compareToIgnoreCase(string2);

Here in the above syntax, string1 and string2 are the strings that would be compared irrespective of the case sensitivity.

concat(): The string concatenation is used to join two strings in Java.

Syntax

string1.concat(string2);\

The characters stored in string2 will be appended after string1.

contains(): A character or set of characters can be searched to look at whether they are present in a string or not. Moreover, it returns the Boolean value(true or false):

Syntax

string.contains("character(s)");

The set of character(s) is searched within the string.

contentEquals(): This method returns true of false and checks whether the characters being searched are equal to the string or not.

Syntax

string.contentEquals("characters");


The <strong>characters</strong> are matched with the <strong>string</strong> and return true on complete match otherwise false.

<strong>startswith(): </strong>This method is used to check whether the string starts with specific character(s) or not.

<strong>Syntax</strong>

[cc lang="java"  width="100%" height="100%" escaped="true" theme="blackboard" nowrap="0"]
string.startswith("character(s)");

endsWith(): This method checks that the string ends with a specific character(s) or not.

Syntax

string.endsWith("character(s)");

equals(): This method matches two strings character by character and returns true on a successful match otherwise false.

Syntax

string1.equals(string2);

The string1 and string2 represent the strings that are going to be checked for equality.

equalsIgnoreCase(): This method checks for the equality of two strings sensitivity.

Syntax

string1.equalsIgnoreCase(string2);

matches(): This method checks whether the regular expression is contained in the string or not.

Syntax

string.matches("regex");

The regex represents the regular expression being searched and the regex comprises of sequential characters.

isEmpty(): This method looks for an empty string and returns the Boolean value.

Syntax

string.isEmpty();

indexOf(): This returns the index of a character when it first occurred in a string.

Syntax

string.indexOf("character");

lastIndexOf(): Returns the position of the last occurrence of a given character(s).

Syntax

string.lastIndexOf("character");

replace(): This method replaces the specific character with a new character in a string.

Syntax

string.replace("old-char", "new-char");

The old-char represent the character that will be replaced by the new-char in a string.

replaceFirst(): This method replaces the first occurrence of a specific regular expression in a string.

Syntax

string.replaceFirst("old-regex","new-regex");

The above syntax is described as the old-regex(regular expression) will be replaced by new-regex(regular expression). The regular expression comprises of sequential characters of a string.

replaceAll(): This method replaces all the occurrences of a specified regular expression(set of characters) in a string.

Syntax

string.replaceAll("ole-regex", "new-regex");

intoLowerCase(): used to convert the string characters to lower case.

Syntax

string.toLowerCase();

toUpperCase(): Used to change the characters to uppercase.

Syntax

string.toUpperCase();

trim(): Any white spaces at the start or end will be removed using trim().

Syntax

string.trim();

hashCode(): This method shows the hash code of the string. The hash code is the memory address of an object to manipulate that object inside hash tables.

Syntax

string.hashCode()

Note: The string used in the above syntaxes refers to the name of the string object.

Conclusion

Java Strings are objects that represent sequences of characters. This article presents the fundamental concepts, working, and usage of strings. Java supports two methods to initialize strings: using a string literal or using a new operator. However, the string literal method is used mostly to initialize a string as it is memory efficient. Additionally, several Java String class methods are also discussed that extend the functionality of a string object.

About the author

Adnan Shabbir