What is String Manipulation?
A string is a sequence of characters, and string manipulation means working with or changing strings. They are widely used in Java. In Java, a string is not a primitive type. It is an object used to create and store text (which is immutable). Simply put, you can think of a string as a constant because it cannot be changed once created. In Java, we do a lot of things with the help of strings. You can also think of a string as an array of characters. Let us see how we can represent the string “GREEN”:
G R E E N
Now, before diving deep into string manipulation in Java, let’s have a quick talk over some basic things about the string that you need to know.
Why do we use Strings?
It’s clear that processing human language is one of the main functions of modern computer science.
This is really important, as language symbols are important to meaning and decision making, and numbers are important to maths. But most of this processing happens in the background, invisible to the user because all of these processing works going on in the background. Although the process is highly precise and accurate.
So in Java, we can consider String as our best friend, and if you want to become a good Java developer, remember that the String class is one of your most important tools.
Also Read: Palindrome in JAVA
Learn Java the right way! Our course teaches you essential programming skills, from coding basics to complex projects, setting you up for success in the tech industry.
How to create a String?
We have mainly two ways to create strings in Java:
- String Literal
- Using new keyword
i) By Using String literal
In Java, we can create strings by assigning a string literal to the String instance;
String str1 = "GreatLearning";
String str2 = "GreatLearning";
As you already know that String is an object in Java. But, above we’ve not created any string object using the new keyword. The compiler handles that task for us. It creates a string object having the string literal (which is provided by us called “GreatLearning”) and then assigns it to provided string instances.
However, it doesn’t create a new object if the object already exists in the memory. Moreover, it will assign the same object to new instances. So, it is clear that even if we have two string instances (str1 and str2), the compiler creates only one string object (value= “GreatLearning”) and it’ll assign the same to both instances. To make it more clear, let’s consider an example. Imagine there are 15 string instances having the same value, so you should know that there’s only one object having the value and all of the 15 string instances would be pointing to the same object.
So, the question is what if we want to have two different objects with the same string? Well for that we need to create strings.
Also Read: Exception Handling in Java with Examples
ii) By Using New Keyword
When we try to assign the same string object to two different literals, compilers only create one and make both literals to point the same object. So by using this, we can easily get out of this problem.
String str1 = new String("GreatLearning");
String str2 = new String("GreatLearning");
Thus by using this, the compiler will create two different objects in memory having the same string.
Example of a simple Java String
public class Example{
public static void main(String args[]){
//creating a string by java string literal
String str = "ModernIndia ";
char[] arrch = {'G','r','e','a','t','L','e','a','r','n','i','n','g'};
//converting the char array arrch[] to string str2
String str2 = new String(arrch);
//creating another java string ‘str3’ by using new keyword
String str3 = new String("String Example");
//Displaying all the three strings
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Output:
ModernIndia
GreatLearning
String Example
String Length
The methods which are used to obtain information about an object are known as accessor methods. length()
method is one of the accessor methods, you can use it with String. Here, the number of characters contained in the string object.
Example:
public class StringExample {
public static void main(String args[]) {
String s1 = "Begin your learning journey today";
System.out.println("The length of String is : " + s1.length());
}
}
The output will be:
The length of String is : 29
What is Concatenating Strings?
Concatenation means joining two or more strings together. Let’s clear it with the help of a simple example:
Consider we have two strings str1 = "Green"
and str2 = "Tea"
. If we combine these two strings, then we should have a result as str3 = "GreenTea"
.
Here, we have basically two methods to perform string concatenation. Check out the code to get a clear picture:
public class String_Example{
public static void main(String[] args){
//String Concatenation
String str1 = "Green";
String str2 = "Tea";
//Method 1 : Using concat
String str3 = str1.concat(str2);
System.out.println(str3);
//Method 2 : Using "+" operator
String str4 = str1 + str2;
System.out.println(str4);
}
}
Java String Methods
char charAt(int index)
: It always returns the character at the specified index. The specified index value always should be between 0 tolength() - 1
(both inclusive). Also, it throwsIndexOutOfBoundsException
ifindex < 0
or>= length of String
.int compareTo(String string)
: It helps to compare the two strings based on the Unicode value of each character in the strings.boolean startsWith(String prefix)
: It checks whether the string starts with the specified prefix. If yes, then it returnstrue
, elsefalse
.boolean equals(Object obj)
: It compares the string with the specified string and returnstrue
if both match, else it’ll printfalse
.int compareToIgnoreCase(String string)
: This is similar to thecompareTo
method, but it ignores case during comparison.boolean startsWith(String prefix, int offset)
: It always checks whether the substring (which is starting from the specified offset index) has the specified prefix or not.int hashCode()
: It always returns the hash code of the string.boolean equalsIgnoreCase(String string)
: It’s not much different than theequals
method. It works the same as theequals
method but it doesn’t consider the case while comparing the strings. Also, it does a case insensitive comparison.int indexOf(String str)
: It returns the index of the first occurrence of the specified substringstr
.boolean endsWith(String suffix)
: It checks whether the string ends with the specified suffix or not.int indexOf(int ch)
: It returns the index of the first occurrence of the specified characterch
in the string.int lastIndexOf(int ch)
: It always returns the last occurrence of the characterch
in the string.int lastIndexOf(int ch, int fromIndex)
: This is the same aslastIndexOf(int ch)
method, and it starts searching fromfromIndex
.int lastIndexOf(String str)
: It returns the index of the last occurrence of stringstr
.String substring(int beginIndex)
: This method helps to return a substring from the string. This substring starts from the specified index.int indexOf(int ch, int fromIndex)
: This is the same as theindexOf
method, however, as you know it starts searching in the string from the specifiedfromIndex
.String concat(String str)
: It always concatenates the specified string “str” at the end of the string like we explained above with an example.String substring(int beginIndex, int endIndex)
: It always returns the substring. Moreover, the substring starts with a character atbeginIndex
and ends with the character atendIndex
.boolean contains(CharSequence s)
: This will check whether the string contains the specified sequence of char values or not. And if yes, then it returns true, else false. It throws aNullPointerException
if the input is null.String toUpperCase()
: This is equivalent totoUpperCase(Locale.getDefault())
.String replace(char oldChar, char newChar)
: This method helps to return the new updated string after changing all the occurrences ofoldChar
with thenewChar
.public String intern()
: It searches the specified string in the memory pool and if it is found, then it returns the reference of it, else it’ll allocate the memory space to the specified string by assigning reference to it.String toUpperCase(Locale locale)
: This method helps to convert the string to upper case string with the help of the rules defined by specified locale.String replaceAll(String regex, String replacement)
: This string method replaces all the occurrences of substrings which are fit to the regular expressionregex
with thereplacement
string.public static String join(CharSequence delimiter, CharSequence... elements)
: It helps in joining the given strings using the specified delimiter and it returns the concatenated Java String.String[] split(String regex)
: It is almost the same assplit(String regex, int limit)
method although it does not have any threshold limit.public boolean isEmpty()
: It returnstrue
if the given string has 0 length. And if the length of the specified Java String is non-zero then it’ll returnfalse
.String toLowerCase()
: This string method is equivalent totoLowerCase(Locale.getDefault())
.String replaceFirst(String regex, String replacement)
: This method replaces the first occurrence of a substring which is fit to the given regular expression “regex” with the specified replacement string.String toLowerCase(Locale locale)
: This string method converts the string to lowercase string using the rules defined by the given locale.public static String format(String format, Object... args)
: It helps in returning a formatted Java String.String[] split(String regex, int limit)
: This string method splits the string and returns the array of substrings that matches the given regular expression. Also, limit is a result threshold here.static String copyValueOf(char[] data, int offset, int count)
: This string method isn’t very different from the above method. Moreover, it comes up with two extra arguments called length of subarray and initial offset of subarray.String trim()
: This string method always returns the substring after omitting leading and trailing white spaces from the original string.static String copyValueOf(char[] data)
: This string method returns a string that contains the characters of the specified character array.char[] toCharArray()
: It converts the string to a character array.static String valueOf(type arg)
: It returns a string representation of passed arguments such as int, long, float, double, char and char array.boolean contentEquals(StringBuffer sb)
: This string method compares the string to the specified string buffer.boolean regionMatches(int srcoffset, String dest, int destoffset, int len)
: This string method compares the substring of the input to the substring of the specified string.void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin)
: This string method always copies the characters of the src array to the dest array. Only the specified range is being copied (srcBegin to srcEnd) to dest subarray (starting from destBegin).boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len)
: This method is another variation of theregionMatches
method with the extra boolean argument to specify whether the comparison is case insensitive or case sensitive.byte[] getBytes(String charsetName)
: This method simply converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.byte[] getBytes()
: It is very similar to the above method but it just uses the default charset encoding for converting the string into sequence of bytes.int length()
: This string method is used to return the length of a String.int codePointAt(int index)
: This method is similar to thecharAt
method however it returns the Unicode code point value of the specified index rather than the character itself.boolean matches(String regex)
: It is used to check whether the String is matching with the specified regular expressionregex
or not.