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

NameDescriptionReturn Value
charAt()Returns the character at the specified indexchar
codePointAt()Returns the unicode code point at the given indexint
codePointBefore()Returns the unicode code point before the given indexint
codePointCount()Returns the number of unicode code pointsint
compareTo()Compares two strings lexicographicallyint
compareToIgnoreCase()Compares two strings lexicographically, ignoring caseint
concat()Appends a string to the end of this stringString
contains()Checks if the string contains the given sequenceboolean
contentEquals()Checks string equality based on contentboolean
copyValueOf()Returns a String created from the chars in char arrayString
endsWith()Checks if the string ends with given suffixboolean
equals()Compares string equalityboolean
equalsIgnoreCase()Compares string equality ignoring caseboolean
format()Returns formatted string using given format and argsString
getBytes()Converts string to byte arraybyte[]
getChars()Copies characters from string into char arrayvoid
hashCode()Returns the hash code of the stringint
indexOf()Returns index of first occurrence of character/stringint
intern()Returns an interned stringString
isEmpty()Checks if string is emptyboolean
lastIndexOf()Returns last index of character/stringint
length()Returns the length of the stringint
matches()Checks if string matches given regexboolean
offsetByCodePoints()Returns offset index based on unicode code pointsint
regionMatches()Checks if region matches given stringboolean
replace()Replaces matches with given replacementString
replaceFirst()Replaces first match with replacementString
replaceAll()Replaces all matches with replacementString
split()Splits string around given regexString[]
startsWith()Checks if string starts with given prefixboolean
subSequence()Returns a sequence of chars from stringCharSequence
substring()Returns a substring given begin/end indexesString
toCharArray()Converts string to a character arraychar[]
toLowerCase()Returns lower case version of stringString
toString()Returns the string itselfString
toUpperCase()Returns upper case version of stringString
trim()Removes leading and trailing whitespaceString
valueOf()Returns a String representation of objectString

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

courses
Image

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

Your email address will not be published. Required fields are marked *