рдореБрдЦреНрдп рд╕рд╛рдордЧреНрд░реА рдкрд░ рдЬрд╛рдПрдБ

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