Summary: In this tutorial, you will learn about String class in Java, how to create them and various operations that can be performed on String in Java.

String in Java

In Java, a string is a sequence of characters. Strings are immutable, which means that once you create a string, you cannot change it.

To represent a string in Java, you need to use the String class.

String str1 = "Hello";

Here, we are creating a string called str1 and assigning it the value “Hello”. This creates a new string object in memory that contains the characters ‘H’, ‘e’, ‘l’, ‘l’, ‘o’.

This is called a string literal, and it is the most common way to create a string in Java. When you create a string literal, the Java compiler automatically creates a String object with the given value.

The String class is defined in the java.lang package, so you don’t need to import it in order to use it. You can use strings in your code simply by enclosing the characters in double quotes.

Other ways to Create String

You can also create a string using a character array, like the following:

char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str2 = new String(charArray);

This creates a new String object with the contents of the character array.

Another approach to create a string is by using a string constructor. The String class has a constructor that takes a string as an argument and creates a new String object with the same contents as the original string.

This can be done with the following code:

String str3 = new String("Hello");

This creates a new String object with the value “Hello”.

Java String Operations

Here is a list of some common operations that you can perform on strings in Java:

1. Concatenation

You can concatenate two strings using the + operator, or by using the concat() method.

String str1 = "Hello";
String str2 = "World";

// Using the + operator
String str3 = str1 + ", " + str2;  // str3 is "Hello, World"

// Using the concat() method
String str4 = str1.concat(", ").concat(str2);  // str4 is "Hello, World"

2. Length

You can find the length of a string using the length() method.

String str = "Hello, World!";
int length = str.length();  // length is 13

3. Substring

You can extract a substring from a string using the substring() method. You can specify the start and end index of the substring that you want to extract.

String str = "Hello, World!";

// Extract the first 5 characters
String sub1 = str.substring(0, 5);  // sub1 is "Hello"

// Extract the characters from index 7 to the end of the string
String sub2 = str.substring(7);  // sub2 is "World!"

4. Index of a character/substring

You can find the index of the first occurrence of a character or a substring in a string using the indexOf() method. You can also find the index of the last occurrence of a character or a substring using the lastIndexOf() method.

String str = "Hello, World!";

// Find the index of the first occurrence of the letter 'o'
int index1 = str.indexOf('o');  // index1 is 4

// Find the index of the last occurrence of the letter 'o'
int index2 = str.lastIndexOf('o');  // index2 is 7

// Find the index of the first occurrence of the substring "World"
int index3 = str.indexOf("World");  // index3 is 7

// Find the index of the last occurrence of the substring "World"
int index4 = str.lastIndexOf("World");  // index4 is 7

5. Compare strings

You can compare two strings using the equals() method or the compareTo() method. The equals() method compares the contents of two strings, while the compareTo() method compares the lexicographic order of two strings.

String str1 = "Hello";
String str2 = "World";

// Using the equals() method
if (str1.equals(str2)) {
    System.out.println("The strings are equal.");
} else {
    System.out.println("The strings are not equal.");
}

// Using the compareTo() method
if (str1.compareTo(str2) < 0) {
    System.out.println("str1 comes before str2 lexicographically.");
} else if (str1.compareTo(str2) > 0) {
    System.out.println("str1 comes after str2 lexicographically.");
} else {
    System.out.println("str1 is the same as str2 lexicographically.");
}

6. Modify strings

Since strings are immutable, you cannot modify them directly. However, you can create a new string that is a modified version of an existing string. For example, you can use the replace() method to replace a substring with another string, or the toLowerCase() or toUpperCase() method to change the case of a string.

String str = "Hello, World!";

// Replace the substring "World" with "Universe"
String modified = str.replace("World", "Universe");  // modified is "Hello, Universe!"

// Convert the string to uppercase
String upperCase = str.toUpperCase();  // upperCase is "HELLO, WORLD!"

// Convert the string to lowercase
String lowerCase = str.toLowerCase();  // lowerCase is "hello, world!"

7. Split a string

You can split a string into an array of substrings using the split() method. You can specify a delimiter string that is used to split the string.

String str = "Hello, World! How are you?";

// Split the string at the spaces
String[] words = str.split(" ");  // words is an array of ["Hello,", "World!", "How", "are", "you?"]

8. Trim a string

You can remove leading and trailing whitespace from a string using the trim() method.

String str = "   Hello, World!   ";

// Remove leading and trailing whitespace
String trimmed = str.trim();  // trimmed is "Hello, World!"

Immutable property of String

In Java, strings are immutable, which means that once you create a string, you cannot change it. For example, consider the following code:

String str = "Hello";
str = str + ", World!";

In this code, we create a string "Hello" and then try to modify it by appending “, World!”. However, what this code actually does is create a new string "Hello, World!" and assign it to the str variable.

The original string "Hello" remains unchanged and can no longer be accessed.

The immutability of strings has some important consequences:

  1. Strings are thread-safe: Since strings cannot be modified, multiple threads can access and operate on the same string without any risk of data corruption.
  2. Strings are more efficient for certain operations: Because strings are immutable, the Java runtime can optimize the memory usage of strings and perform certain operations more efficiently. For example, when you concatenate two strings, the Java runtime can simply allocate a new string that is the concatenation of the two original strings, without having to copy the characters from the original strings.
  3. Strings are easier to reason about: Since strings cannot be modified, you don’t have to worry about the state of a string changing unexpectedly. This can make it easier to reason about your code and debug issues.

However, the immutability of strings can also be a drawback in some cases.

For example, if you need to perform many operations that modify a string, such as replacing substrings or changing the case of the string, you will have to create a new string for each operation, which can be less efficient than modifying an existing string in-place.

In these cases, you might consider using a mutable alternative to String, such as a StringBuilder.


Leave a Reply