Java String Methods with Examples
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Strings are fundamental to most programming languages, and Java is no exception. The Java String class provides robust methods and properties for working with strings in Java code.
In this article, we will explore the ins and outs of Java strings to understand how to work with and manipulate strings efficiently in Java.
A Java string is an object that represents a sequence of characters. The String class in Java belongs to the java.lang package, so we don’t need to import it explicitly. We will examine how to create strings, what everyday operations are available, and best practices for handling strings. Mastering the Java String class is vital to writing optimized Java code for text manipulation or processing.
Creating Strings in Java
There are a few different ways to create a new Java string:
The Java String Class Constructor
We can create a string by calling the String constructor and passing a char array:
char[] myChars = {'H', 'e', 'l', 'l', 'o'};
String myString = new String(myChars);
System.out.println(myString); // Prints "Hello"String Literals
We can also use string literals enclosed in double quotes:
String greeting = "Hello World!";
Converting Other Data Types to Strings
The String class provides methods for converting other data types like integers, floats, etc. to strings:
int age = 30; String ageString = String.valueOf(age); float pi = 3.14f; String piString = String.valueOf(pi);
Common String Operations
| Name | Description | Return Value |
| charAt() | Returns the character at the specified index | char |
| codePointAt() | Returns the unicode code point at the given index | int |
| codePointBefore() | Returns the unicode code point before the given index | int |
| codePointCount() | Returns the number of unicode code points | int |
| compareTo() | Compares two strings lexicographically | int |
| compareToIgnoreCase() | Compares two strings lexicographically, ignoring case | int |
| concat() | Appends a string to the end of this string | String |
| contains() | Checks if the string contains the given sequence | boolean |
| contentEquals() | Checks string equality based on content | boolean |
| copyValueOf() | Returns a String created from the chars in char array | String |
| endsWith() | Checks if the string ends with given suffix | boolean |
| equals() | Compares string equality | boolean |
| equalsIgnoreCase() | Compares string equality ignoring case | boolean |
| format() | Returns formatted string using given format and args | String |
| getBytes() | Converts string to byte array | byte[] |
| getChars() | Copies characters from string into char array | void |
| hashCode() | Returns the hash code of the string | int |
| indexOf() | Returns index of first occurrence of character/string | int |
| intern() | Returns an interned string | String |
| isEmpty() | Checks if string is empty | boolean |
| lastIndexOf() | Returns last index of character/string | int |
| length() | Returns the length of the string | int |
| matches() | Checks if string matches given regex | boolean |
| offsetByCodePoints() | Returns offset index based on unicode code points | int |
| regionMatches() | Checks if region matches given string | boolean |
| replace() | Replaces matches with given replacement | String |
| replaceFirst() | Replaces first match with replacement | String |
| replaceAll() | Replaces all matches with replacement | String |
| split() | Splits string around given regex | String[] |
| startsWith() | Checks if string starts with given prefix | boolean |
| subSequence() | Returns a sequence of chars from string | CharSequence |
| substring() | Returns a substring given begin/end indexes | String |
| toCharArray() | Converts string to a character array | char[] |
| toLowerCase() | Returns lower case version of string | String |
| toString() | Returns the string itself | String |
| toUpperCase() | Returns upper case version of string | String |
| trim() | Removes leading and trailing whitespace | String |
| valueOf() | Returns a String representation of object | String |
Example
This Java code showcases examples of some of the most commonly used String methods in Java, including charAt(), length(), indexOf(), substring(), and equals(), demonstrating their practical usage with a sample string.
public class StringMethodsExample {
public static void main(String[] args) {
// Define a sample string
String text = "Hello, World!";
// 1. charAt() - Accessing a character at a specific index
char character = text.charAt(7);
System.out.println("Character at index 7: " + character);
// 2. length() - Getting the length of the string
int length = text.length();
System.out.println("Length of the string: " + length);
// 3. indexOf() - Finding the position of a character or substring
int indexOfComma = text.indexOf(",");
System.out.println("Index of ',' in the string: " + indexOfComma);
// 4. substring() - Extracting a substring from the original string
String subString = text.substring(0, 5); // Extract "Hello"
System.out.println("Substring: " + subString);
// 5. equals() - Comparing two strings for equality
String anotherText = "Hello, World!";
boolean areEqual = text.equals(anotherText);
System.out.println("Are the two strings equal? " + areEqual);
}
}Output:
Character at index 7: W
Length of the string: 13
Index of ‘,’ in the string: 5
Substring: Hello
Are the two strings equal? true
String Handling Best Practices
When working with Java strings, following best practices can help optimize your code:
Immutability of String Objects: String objects are immutable in Java—the value of a string cannot be changed once created, making them thread-safe. Any operation that modifies a string returns a new string object. Keep this in mind to avoid unintended reference changes.
Avoid Excessive String Concatenation: Using the + operator to concatenate strings excessively can create multiple string objects. Consider using a StringBuilder instead when programmatically generating long strings.
Use StringBuilder for Efficient String Manipulation: Methods like substring() and concat() return new string instances. For repeated string manipulations, StringBuilder is preferred over manual concatenation.
Conclusion
The Java String class provides rich methods and properties for working with strings. Its capabilities make creating, comparing, searching, extracting, replacing, and converting strings easy. Best practices, such as avoiding unnecessary String object creations, ensure optimal use of memory and CPU.
This article covered the basics of Java strings – different ways to create strings, joint string operations, and string handling best practices. The String class is fundamental to Java programming, and mastering it will help you write more efficient code that works with text.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google

