Java Strings



In this tutorial, we will learn about Java Strings, how to create them, and the different String class methods with the help of examples.


Java Strings

Strings are used for storing text.

In Java, a string is a sequence of characters.

In Java, to represent a string, we use double-quotes. For example,

// create a string
String greeting = "Hello";

Here, we have created a string variable named greeting. The variable is initialized with the string Hello.


Example: Creating a String in Java

In the following example, we will see how to create a string in Java,

public class Main {
    public static void main(String[] args) {

        // create strings 
        String a = "Hello";
        String b = "Java";
        String c = "Awesome";

        // print strings
        System.out.println(a);    // print Hello
        System.out.println(b);    // print Java
        System.out.println(c);    // print Awesome
    }
}

Output:

Hello
Java
Awesome

Here above, we have created three strings named a, b, and c. Here, we are creating strings like primitive types.

There is another way of creating Java strings (using the new keyword). We will see more about it in this tutorial.

Note: In Java, strings are not primitive types (like int, char, etc). Instead, all strings are objects of a predefined class named String.

In Java, all string variables are instances of the String class.


Java String Operations

Java String class offers different methods to perform various operations on strings. Let us see some of the most used string operations.


How to Get the length of a String?

The length() method is used to find the length of a string. For example,

public class Main {
    public static void main(String[] args) {
        
        // create a string 
        String greeting = "Hello World";
        System.out.println("String: " + greeting);

        // get the length of the greeting variable
        int length = greeting. length();
        System.out.println("Length: " + length);
    }
}

Output:

String: Hello World
Length: 11

Here above, the length() method returns the total number of characters in the string.


How to Join Two Java Strings?

The concat() is used to join two strings in Java. For example,

public class Main {
    public static void main(String[] args) {
        
        // create first string
        String firstStr = "Hello ";
        System.out.println("First String: " + firstStr);

        // create second string
        String secondStr = "World";
        System.out.println("Second String: " + secondStr);

        // join two strings
        String joinedStr = firstStr.concat(secondStr);
        System.out.println("Joined String: " + joinedStr);
    }
}

Output:

First String: Hello 
Second String: World
Joined String: Hello World

Here above, we have created two strings named firstStr and secondStr. We used the concat() method to join the secondStr to the firstStr string and assign it to the joindedStr variable.

To join two strings in Java, we can also use the plus + operator.


How to compare two Strings?

The equals() method is used to make comparisons between two strings. For example,

public class Main {
    public static void main(String[] args) {
        
        // create 3 strings
        String first = "Hello World";
        String second = "Hello World";
        String third = "Java is awesome";

        // compare first and second strings
        boolean result1 = first.equals(second);
        System.out.println("Strings first and second are equal: " + result1);

        // compare second and third strings
        boolean result2 = second.equals(third);
        System.out.println("Strings second and third are equal: " + result2);
    }
}

Output:

Strings first and second are equal: true
Strings second and third are equal: false

Here above, we have created 3 strings, and we used the equal() method to verify if one string is equal to another.

The equals() method checks the content of strings while comparing them.


Escape character in Java Strings

In Java, the escape character is used to escape some of the characters present inside a string.

Let us suppose we need to include double quotes inside a string.

// include double quote 
String text = "The most used programming language is "Java"";

Here above, the code will cause an error. Since strings are represented by double-quotes, the compiler will treat "The most used programming language is".

The solution for this issue is to use the escape character \ in Java. For example,

// use the escape character 
String text = "The most used programming language is \"Java\"";

Here, the escape characters are used to tell the compiler to escape double-quotes and read the whole text.


Java Strings are Immutable

In Java, when we create a string, the string is immutable, which means once we create a string, we cannot change that string.

Let us see the following example:

// create a string
String text = "Java ";

Here, we have created a string variable named text. The variable holds the string "Java "

Now, let us say that we want to change the string.

// add another string "programming language"
text = text.concat("programming language");

Above, we used the concat() method to add another string "programming language" to the previous string.

It seems like we are able to change the value of the previous string. However, this is not the reality.

So let us see what has happened here,

  1. JVM takes the first string "Java "
  2. Creates a new string by adding "programming language"
  3. Assign the new string "programming language" to the text variable
  4. The first string "Java " remains unchanged (immutable)

Creating strings using the new keyword

Before now, we have created strings like primitive types in Java.

Strings in Java are objects, so we can create strings using the new keyword. For example,

// create a string using the new keyword
String hello = new String("Hello World");

Here above, we have created a string hello using the new keyword.

In Java, when we create a string object, the String() constructor is invoked automatically.

Note: The String class offers different other constructors to create strings. You can visit the official Java documentation of the Java String.


Example: Create Java Strings using the new keyword

In the following example, we will create a Java string using the new keyword.

public class Main {
    public static void main(String[] args) {
        
        // create a string using the new keyword
        String hello = new String("Hello World");

        System.out.println(hello);
    }
}

Output:

Hello World

The difference between creating String using literals and the new keyword

Now that we know how to create stings using literals and the new keyword, let us see the significant difference between the two options.

In Java, the JVM keeps a string pool to store all of its strings inside the memory. The string pool helps in reusing the strings.

  1. Creating strings using string literals,

    String hello = "Hello World";
    

    Here above, we are directly providing the value of the string Hello World . The compiler first verifies the string pool to see if the string already exists.

    • If the string already exists in the string pool, the new string is not created. Instead of returning the new reference, the hello variable points to the already existing "Hello World" string.
    • If the string does not exist, the new string "Hello World" is created.
  2. Creating strings using the new keyword,

    String hello = new String("Hello World");
    

    Here above, the value of the string is not directly provided. Even if the "Hello World" string already exists, a new "Hello World" string is created.


Java String Methods

Method Description Return Type
chartAt() Returns the character at the specified index char
codePointAt() Returns the Unicode of the character at the specified index int
codePointBefore() Returns the Unicode of the character before the specified index int
codePointCount() Returns the number of Unicode value found in a string int
compareTo() Compares two strings lexicographically int
compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences int
concat() Appends a string to the end of another string String
contains() Checks if a string contains a sequence of characters or not boolean
contentEquals() Checks of a string contains the exact same sequence of characters of the specified CharSequence or StringBugger boolean
copyValueOf() Returns a String that represents the characters of the character array String
endsWith() Checks if string ends with the specified character(s) boolean
equals() Compares two strings. Returns true of the strings are equal, and false if not boolean
equalsIgnoreCase() Compares two strings, ignoring case considerations boolean
format() Returns a formatted string using the specified locale, format string, and arguments String
getBytes() Encodes a String into a sequence of bytes using the names charset, storing the result into a new byte array byte[]
getChars() Copies characters from a string to an array of chars void
hashCode() Returns the hash code of a string int
indexOf() Returns the position of the first found occurrence of specified characters in a string int
intern() Returns the canonical representation for the string object String
isEmpty() Checks if a string is empty or not boolean
lastIndexOf() Returns the position of the last found occurrence of specified characters in a string int
length() Returns the length of a specified string int
matches() Searches a string for a match against a regular expression, and returns the matches boolean
offsetByCodePoints() Returns the index within this String that is offset from the given index by codePointOffset code points int
regionMatches() Checks if two string regions are equal boolean
replace() Searches a string for a specified value, and returns a new string where the specified values are replaced String
replaceFirst() Replaces the first occurrence of a substring that matches the given regular expression with the given replacement String
replaceAll() Replaces each substring of this string that matches the given regular expression with the given replacement String
split() Splits a string into an array of substrings String[]
startWith() Checks whether a string starts with specified characters boolean
subSequence() Returns a new character sequence that is a subsequence of this sequence CharSequence
substring() Returns a new string which is the substring of a specified string String
toCharArray() Converts this string to a new character array char[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends of a string String
valueOf() Returns the string representation of the specified value String


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.