String class in Java

The String class in Java is a fundamental class in the Java Standard Library. It is one of the most widely used classes in the Java programming language. It represents a sequence of characters and provides a number of methods for manipulating strings.

One of the most important characteristics of the String class is that it is immutable, meaning that once a String object is created, its value cannot be changed. This makes String objects thread-safe, as they cannot be modified by multiple threads simultaneously.

Common methods of String class in Java

MethodDescription
charAt()Returns the character at a specified index in the string.
concat()Appends one string to the end of another string.
contains()Checks if the string contains a specified substring.
indexOf()Returns the index of the first occurrence of a specified substring in the string.
lastIndexOf()Returns the index of the last occurrence of a specified substring in the string.
length()Returns the length of the string.
replace()Replaces all occurrences of a specified substring with another substring.
split()Splits the string into an array of strings using a specified delimiter.
toLowerCase()Converts the string to lowercase.
toUpperCase()Converts the string to uppercase.

Following are some examples of the methods available in the String class:

concat()

This method concatenates (joins) the two strings and returns a new string. Let’s see an example below:

String firstName = "Virat";
String lastName = "Kohli";

To print the full name Virat Kohli, we need to concat these two strings. See the example below:

firstName.concat(lastName);
System.out.println(firstName);

If we print firstName then it will print Virat. This is because String is an immutable object. This basically means, once the string is created it can’t be modified. To create a mutable string we have StringBuilder and StringBuffer in Java.

To print fullName we need to assign it to a new variable like:

String fullName = firstName.concat(lastName);
System.out.println(fullName);

This prints the output:

Virat Kohli

length()

This method counts the number of characters in the string and returns the value.

Let’s take an example of the following code:

String str = "Hello, world!";
int length = str.length();  // length is 13
System.out.println(length);

The output of the above code will be:

13

Because in the variable str there are 13 characters. Remember that the space is also a character.

charAt(int index)

This method returns the character at the specified index in the string.

Let’s take an example of the following code:

String str = "Hello, world!";
char c = str.charAt(1);
System.out.println(c);

The output of the following code will be:

e

Because the starting index is zero (0). Hence, e is in the 1th position of the variable str.

substring(int beginIndex, int endIndex)

This method returns a new string that is a substring of the original string. Starting at the specified beginIndex and ending at the specified endIndex - 1.

Let’s consider the following example:

String str = "Hello, world!";
String sub = str.substring(7, 12); 
System.out.println(sub);

The output of the above code will be:

world

indexOf(String str)

This method returns the index of the first occurrence of the specified string in the original string. For example:

String str = "Hello, world!";
int index = str.indexOf("world"); 
System.out.println(index);

The output of the above code will be:

7

Since this method returns the index of the first occurrence of the specified string, the following code also returns the same output:

String str = "Hello, world from the Coder Sathi World.";
int index = str.indexOf("world");  // index is 7
System.out.println(index);

The output of the above code is also the same. i.e. 7.

toLowerCase() and toUpperCase()

These methods return a new string with all the characters in the original string converted to lowercase or uppercase, respectively. See the example below:

String str = "Hello, world!";
String lower = str.toLowerCase();  // lower is "hello, world!"
String upper = str.toUpperCase();  // upper is "HELLO, WORLD!"

trim()

This method returns a new string with leading and trailing whitespace removed. See the example below:

String str = "   Hello, world!   ";
String trimmed = str.trim();  // trimmed is "Hello, world!"

If we print the length of the str before and after print we will get:

String str = "   Hello, world!   ";
System.out.println("Before trim: "+str.length());
String trimmed = str.trim();  
System.out.println("After trim: "+trimmed.length());

Output:

Before trim: 19
After trim: 13

Here, the original String value str has two spaces before and after Hello, world! text.

split(String regex)

This method splits the string into an array of substrings, using the specified regular expression as the delimiter. See the example below:

String str = "Hello,world,how,are,you,today";
String[] words = str.split(",");  // words is ["Hello", "world", "how", "are", "you", "today"]

There are many methods in the String class. You can refer to the official documentation to understand them in detail.

FAQs

What is the String class in Java?

The String class in Java is a class that represents a sequence of characters. It is part of the Java Standard Library and provides various methods for manipulating and working with strings.

How do I create a String object in Java?

You can create a String object in Java by either using double quotes, like this: String str = "Hello, Coder Sathi";, or by using the String constructor: String str = new String("Hello, Coder Sathi");.

Are String objects in Java mutable or immutable?

String objects in Java are immutable, meaning their values cannot be changed once they are created.

How can I compare two String objects for equality in Java?

To compare two String objects for equality, you should use the equals() method. If both the objects has same value then it will return true otherwise false.

What is the StringBuilder class, and how is it different from String for string manipulation?

The StringBuilder class in Java provides a mutable way to manipulate strings. It is more efficient for tasks involving frequent string modifications compared to the immutable String class.

Can String objects be used in switch statements in Java?

Yes, starting from Java 7, you can use String objects in switch statements for more convenient string-based branching.

How can I convert a String to a numeric data type in Java, such as int or double?

You can use methods like Integer.parseInt(String str) for converting a String to an integer and Double.parseDouble(String str) for converting a String to a double.

Can I use regular expressions with String objects in Java?

Yes, Java provides support for regular expressions through the java.util.regex package. You can use the Pattern and Matcher classes to work with regular expressions and String objects.

What is the concept of string interning in Java?

String interning in Java is a mechanism where multiple references to the same string literal point to a single instance in memory. This is done to conserve memory and improve performance in some cases.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments