Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming

Java Strings

In Java, strings are objects that represent sequences of characters. The String class is part of the java.lang package and provides a range of methods to manipulate and work with strings efficiently. Strings in Java are immutable, meaning that once a String object is created, its value cannot be changed.

Creating Strings

Strings can be created in Java using string literals or by instantiating the String class.

Using String Literals

String literal = "Hello, World!";

Using the String Class

String object = new String("Hello, World!");

Common String Methods

Java provides a robust set of methods to perform various operations on strings. Here are some commonly used methods:

Example 1: Length of a String

public class StringLengthExample {
    public static void main(String[] args) {
        String text = "Hello, World!";
        int length = text.length();
        System.out.println("Length of the string: " + length);
    }
}

The length() method returns the number of characters in the string.

Example 2: String Concatenation

public class StringConcatExample {
    public static void main(String[] args) {
        String firstName = "John";
        String lastName = "Doe";
        String fullName = firstName + " " + lastName;
        System.out.println("Full Name: " + fullName);
    }
}

Strings can be concatenated using the + operator or the concat() method.

Example 3: Substring Extraction

public class SubstringExample {
    public static void main(String[] args) {
        String text = "Hello, World!";
        String sub = text.substring(7, 12);
        System.out.println("Substring: " + sub);
    }
}

The substring(int beginIndex, int endIndex) method extracts a portion of the string from beginIndex to endIndex - 1.

Example 4: Finding a Character in a String

public class IndexOfExample {
    public static void main(String[] args) {
        String text = "Hello, World!";
        int index = text.indexOf('W');
        System.out.println("Index of 'W': " + index);
    }
}

The indexOf() method returns the index of the first occurrence of the specified character or string.

Tips and Best Practices

  • Immutability: Remember that strings are immutable. Any modification results in a new String object being created.
  • StringBuilder/StringBuffer: Use StringBuilder or StringBuffer for mutable strings when performing numerous modifications to avoid creating multiple objects.
    StringBuilder builder = new StringBuilder("Hello");
    builder.append(", World!");
    System.out.println(builder.toString());
    
  • String Pool: Java maintains a string pool to optimize memory usage. Use string literals to take advantage of this feature.
  • Equality Check: Use equals() to compare string values instead of ==, which checks for reference equality.
    String str1 = "Hello";
    String str2 = new String("Hello");
    boolean isEqual = str1.equals(str2); // true
    
  • Null Checks: Always perform null checks before calling methods on strings to avoid NullPointerException.
    if (str != null && str.equals("test")) {
        // Safe to use str
    }