Common Java String methods
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
Check this out, Solid Principles in java
toUpperCase() and toLowerCase() String method
This String is converted to an uppercase letter using the Java String toUpperCase() method and a lowercase letter using the String toLowerCase() method.
Implementation
Java
public class Stringoperation1
{
public static void main(String args[])
{
String str="CodingNinjas";
System.out.println(str.toUpperCase());//CODINGNINJAS
System.out.println(str.toLowerCase());//codingninjas
System.out.println(str);//CodingNinjas(no change)
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
CODINGNINJAS
codingninjas
CodingNinjas
trim() String method
The trim() function of the String class removes white spaces before and after the String and returns the substring.
Implementation
Java
public class Stringoperation2
{
public static void main(String args[])
{
String str=" CodingNinjas ";
System.out.println(str);// CodingNinjas
System.out.println(str.trim());//CodingNinjas
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
CodingNinjas
CodingNinjas
startsWith() and endsWith() String method
The function startsWith() determines if the String begins with the letters supplied as arguments and finishes with the letters passed as arguments. The endsWith() function determines if the String contains the letters provided as parameters.
Implementation
Java
public class Stringoperation3
{
public static void main(String args[])
{
String str="CodingNinjas";
System.out.println(str.startsWith("Co"));//true
System.out.println(str.endsWith("s"));//true
System.out.println(str.endsWith("g"));//false
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
true
true
false
charAt() String method
The charAt() function of the String class returns a character at the provided index. The specified index value must be in the range of 0 to length() -1, inclusive. If index >= length of String, it raises IndexOutOfBoundsException.
Implementation
Java
public class Stringoperation4
{
public static void main(String args[])
{
String str="CodingNinjas";
System.out.println(str.charAt(0));//C
System.out.println(str.charAt(6));//N
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
C
N
length() String method
The length() function of the String class returns the length of the provided String.
Implementation
Java
public class Stringoperation5
{
public static void main(String args[])
{
String str="CodingNinjas";
System.out.println(str.length());//12
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
12

You can also try this code with Online Java Compiler
Run Codeintern() String method
The class String keeps a private pool of strings that is initially empty. If the pool already has a String equal to this String object as determined by the equals(Object) function, the String from the pool is returned when the intern method is called. Otherwise, a reference to this String object is returned, and this String object is added to the pool.
Implementation
Java
public class Stringoperation6
{
public static void main(String args[])
{
String str=new String("CodingNinjas");
String str2=str.intern();
System.out.println(str2);//CodingNinjas
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
CodingNinjas
valueOf() String method
The String class's function valueOf() function converts any type into String, including int, long, float, double, boolean, char, and char array.
Implementation
Java
public class Stringoperation7
{
public static void main(String args[])
{
int x=20;
String str=String.valueOf(x);
System.out.println(str+10);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
2010
replace() String method
The replace() function of the String class replaces all occurrences of the first sequence of characters with the second sequence of characters.
Implementation
Java
public class Stringoperation8
{
public static void main(String args[])
{
String str="C++ is a programming language. C++ is a platform. C++ is an Island.";
String replaceStr=str.replace("C++","Java");//replaces all occurrences of "C++" to "Java"
System.out.println(replaceStr);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Java is a programming language. Java is a platform. Java is an Island.
You can also read about the topic of Java Destructor.
Must Read: String Args in Java
Other Java String methods
- boolean equals(Object obj): If the String and the supplied string match, true is returned; otherwise, false.
- boolean equalsIgnoreCase(String string): It operates in the same way as the equals method, except it doesn't consider the case when comparing strings. It performs a case-insensitive analysis.
- int compareTo(String string): The Unicode value of each character in the strings is used to compare the two strings.
- int compareToIgnoreCase(String string): It's the same as the CompareTo method, but it ignores the case while comparing.
- boolean startsWith(String prefix, int offset): It determines whether or not the substring (beginning at the supplied offset index) has the specified prefix.
- int hashCode(): It returns the String's hashcode.
- int indexOf(int ch): Returns the position in the String where the provided character ch appears for the first time.
- int indexOf(int ch, int fromIndex): It works in the same way as indexOf, except it starts searching in the text from the supplied fromIndex.
- int lastIndexOf(int ch): It returns the String's last occurrence of the character ch.
- int lastIndexOf(int ch, int fromIndex): It starts searching from fromIndex, much as the lastIndexOf(int ch) function.
- int indexOf(String str): The index of the first occurrence of the supplied substring str is returned by this method.
- int lastindexOf(String str): Returns the index of the string str's latest occurrence.
- String substring(int beginIndex): It gives you the String's substring. The character in the supplied index is the first character in the substring.
- String substring(int beginIndex, int endIndex): The substring is returned. At beginIndex, the substring begins with a character and ends with the character at endIndex.
- String concat(String str): At the end of the String, concatenates the provided string "str."
- boolean contains(CharSequence s): It determines if the String has the supplied char value sequence. If yes, it returns true; otherwise, it returns false. When 's' is null, it raises a NullPointerException.
- public boolean isEmpty(): If the provided String has no length, this function returns true. It returns false if the length of the provided Java String is greater than zero.
- public static String join(): This method combines the provided texts using the specified delimiter and returns a Java String that has been concatenated.
- String replaceFirst(String regex, String replacement): It substitutes the provided replacement string for the first occurrence of a substring that matches the given regular expression "regex."
- String replaceAll(String regex, String replacement): It uses the replacement string to replace all occurrences of substrings that match the regular expression regex.
- String[] split(String regex, int limit): It breaks the String into substrings and produces an array that matches the regular expression. Here, the limit is a result threshold.
- String[] split(String regex): The split(String regex, int limit) function is similar to the split(String regex, int limit), except it does not contain a threshold limit.
- public static String format(): This function produces a formatted Java String.
- char[] toCharArray(): The string is converted to a character array.
- static String copyValueOf(char[] data): It returns a string containing the characters from the character array supplied.
- static String copyValueOf(char[] data, int offset, int count): The same procedure as before, but with two additional arguments: the subarray's beginning offset and length.
- void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): The characters from the src array are copied to the dest array. Only the provided range (from srcBegin to srcEnd) is transferred to the dest subarray (starting from destBegin).
- boolean contentEquals(StringBuffer sb): It compares the String to the string buffer that has been supplied.
- boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the input substring to the given String's substring.
- boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variant of the regionMatches function, this time with an additional boolean argument to determine whether the comparison is case sensitive or case insensitive.
- byte[] getBytes(String charsetName): It transforms a String to a series of bytes using the provided charset encoding and returns the array of bytes as a result.
- byte[] getBytes(): This function is identical to the last one, only it converts the String into a series of bytes using the default charset encoding.
- boolean matches(String regex): It determines whether the String matches the regular expression regex that has been supplied.
- int codePointAt(int index): It's identical to the charAt method, except instead of returning the character, it returns the Unicode code point value of the supplied index.
Must Read Array of Objects in Java
Frequently Asked Questions
What is a string method in Java?
A string method in Java refers to built-in functions provided by the String class to manipulate and perform operations on string objects, like length(), substring(), etc.
What is string class with example?
The String class in Java represents a sequence of characters. Example:
String greeting = "Hello";
What is exploring string class in Java?
Exploring the String class in Java involves understanding its methods and properties for manipulating strings, such as concatenation, comparison, and extraction.
Conclusion
In this article, we discussed the String class in Java, which provides a robust array of methods for manipulating and querying text. These methods, from basic string operations like concatenation and substring to more complex functions like matches and replace, are integral for effective text processing in Java. Accessible through the default `java.lang` package, they are essential tools for any Java developer, which enhances both the functionality and versatility of string handling.
We hope this blog has helped you enhance your knowledge regarding the string class methods. If you would like to learn more, check out our articles on Understanding Strings, Strings Operations, and String Interview Questions In Java.
Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problems, Interview experience, Coding interview questions, and the Ultimate guide path for interviews.