Introduction
In this lesson of our Java course, we will learn about the Java string . The Java String
class is a built-in class that represents a sequence of characters. It is one of the most commonly used classes in Java, as it provides a way to store and manipulate text-based data. Here is an overview of the Java String class.
1. Creating a String Object
There are several ways to create a String
object in Java, including:
- String Literals.
- Using
new
keyword. - The
valueOf()
method. - String concatenation.
StringBuilder
.StringBuffer
int
, char
, etc). Instead, all strings are objects of a predefined class named String
.Let’s look at the following example to create Java String
class Main {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "devjournal";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print devjournal
}
}
1.1. Using String Literals
We can create a String
object using a string literal, which is simply a sequence of characters enclosed in double quotes:
String myString = "Hello, World!";
1.2. Using the new
keyword
We can create a String
object using the new
keyword and passing a sequence of characters as an argument to the String
constructor:
String myString = new String("Hello, World!");
Note that this method is less common and less efficient than using string literals, as it creates a new object on the heap every time it is called.
1.3. Using the valueOf()
method
We can create a String
object by converting a non-string object to a string using the valueOf()
method. This method is often used to convert primitive data types to their string representations:
int myInt = 42;
String myString = String.valueOf(myInt);
1.4. Using string concatenation
We can concatenate two or more strings using the +
operator to create a new String
object:
String greeting = "Hello";
String name = "John";
String message = greeting + ", " + name + "!";
StringBuilder
is not thread-safe, while StringBuffer
is thread-safe but slower2. String Operations
The Java String class provides many useful methods for manipulating strings, including methods for getting the length of a string, finding characters or sub-strings within a string, replacing characters or sub-strings within a string, converting a string to uppercase or lowercase, and more.
String str = "Hello, World!";
// length
int len = str.length();
// indexOf
int index = str.indexOf("World");
// substring
String substr = str.substring(0, 5);
// replace
String replacedStr = str.replace("World", "Java");
// toUpperCase
String upperCaseStr = str.toUpperCase();
// toLowerCase
String lowerCaseStr = str.toLowerCase();
2.1. Getting String Length
Finding length of String is a common use case, we can use the length() method of String class to get the length. Let’s see this example for better understanding:
public class LengthExample {
public static void main(String[] args) {
//create string
String str = "Welcome To Javadevjournal!";
//get length
int length = str.length();
System.out.println("The length of the string is: " + length);
}
}
Here is the output:
The length of the string is: 27
2.2. CharAt() Method
The charAt() method is used to get the character at a specific index in a string.
public class CharAtExample {
public static void main(String[] args) {
String str = "Welcome To Javadevjournal!";
char ch = str.charAt(1);
System.out.println("The character at index 1 is: " + ch);
}
}
//output : The character at index 1 is: e
2.3. Substring Method
The substring() method is used to extract a portion of a string. We can specify the starting index and the ending index, and the method will return the substring that starts from the starting index and goes up to, but not including, the ending index.
public class SubstringExample {
public static void main(String[] args) {
String str = "Welcome To Javadevjournal!";
String subStr = str.substring(11, 24);
System.out.println("The substring is: " + subStr);
}
}
Here is the output.
The substring is: Javadevjournal
2.4. IndexOf Method
The indexOf()
method is used to find the index of the first occurrence of a character or a substring in a string. If the character or sub string is not found, the method returns -1.
String str = "Welcome to Javadevjournal";
int index = str.indexOf("o");
System.out.println("The index of the first 'o' is: " + index);
Here is the output:
The index of the first 'o' is: 4
2.5. Compare two Strings
In case we want to compare 2 string, we can use the equals()
method to compare.
class StringCompare {
public static void main(String[] args) {
// create 3 strings
String s1 = "java development";
String s2 = "java development";
String s3 = "java dev journal";
// compare first and second strings
boolean result1 = s1.equals(s2);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings
boolean result2 = s1.equals(s3);
System.out.println("Strings first and third are equal: " + result2);
}
}
Output
Strings first and second are equal: true
Strings first and third are equal: false
3. Java Strings are Immutable
Strings in Java are immutable, so once a String
object is created, its contents cannot be changed. However, we can create new String
objects that are based on the original string by using various methods provided by the String
class.
String str = "Hello, World!";
// create a new string based on the original string
String newStr = str.replace("World", "Java");
// the original string is still unchanged
System.out.println(str); // "Hello, World!"
4. String Pool
In Java, there is a concept of a “string pool,” which is a cache of String
objects that are stored in memory for reuse. This can help to improve performance and reduce memory usage when working with large numbers of String
objects.
String str1 = "Hello, World!";
String str2 = "Hello, World!"; // this string is taken from the string pool
// both strings refer to the same object in memory
System.out.println(str1 == str2); // true
5. String vs StringBuilder vs StringBuffer
Besides the String
class, Java also provides the StringBuilder
and StringBuffer
classes for manipulating strings. While all three classes provide similar functionality, there are some key differences between them, including their mutability, thread-safety, and performance characteristics.
// using StringBuilder
StringBuilder builder = new StringBuilder();
builder.append("Hello");
builder.append(", ");
builder.append("Java!");
String result = builder.toString();
// using StringBuffer
StringBuffer buffer = new StringBuffer();
buffer.append("Hello");
buffer.append(", ");
buffer.append("Java!");
String result2 = buffer.toString();
6. Java String Method
We have only covered a few important methods on the Java string. There are various String methods available in String class. Here is the list of important methods.
Method | Description |
---|---|
join() | join string using the delimiter |
contains() | check if given string contains substring |
indexOf() | returns the position of the specified character in the string |
substring() | return substring of a string |
replace() | replace a character with a given new character |
replaceAll() | replaces all substrings matching the regex pattern |
charAt() | return character at a specific position |
compareTo() | Compare 2 strings |
trim() | removes any leading and trailing white spaces |
split() | Split string in arrays of String based on pattern |
toLowerCase() | Convert String to lower case |
toUpperCase() | Convert String to upper case |
valueOf() | returns the string representation of the specified argument |
matches() | Check if String matches a regular expression |
startsWith() | Check if string start with a given String |
endsWith() | check if String ends with a given string. |
isEmpty() | If a given string is empty. |
compareToIgnoreCase() | compare 2 string ignoring case sensitivity. |
intern() | canonical representation of String |
toCharArray() | Convert given String to char array |
format() | format a given String |
hashCode() | return the hashCode for a given String |
Summary
Overall, the String
class provides a powerful and flexible way to work with strings in Java. By understanding its methods and properties, we can create efficient and effective code for working with text-based data.While the String
class is immutable and may require additional memory allocations for each operation that modifies the string, it is often the best choice for most use cases because of its ease of use, readability, and performance.
As always, the source code of this course is available on our GitHub repository.