Menu

Java Topic

Java Strings

In Java, strings are a core feature, used to represent sequences of characters. Java provides the String class to create and manipulate strings.

1. Creating Strings

Strings in Java can be created in several ways:

  • Using String Literals:
    String str1 = "Hello, World!";
    This creates a string object in the string pool if it doesn't already exist.
  • Using the new Keyword:
    String str2 = new String("Hello, World!");
    This creates a new string object in the heap memory, even if the string already exists in the string pool.

2. String Characteristics

Immutability: Strings in Java are immutable, meaning once a String object is created, its value cannot be changed. Any modification to a string results in the creation of a new string.

String Pool: Java maintains a special memory region called the 'string pool' to store string literals. If a string is created using a literal and already exists in the pool, Java will reuse the reference rather than creating a new object.

3. Common String Methods

Java provides many useful methods to manipulate and work with strings:

  • Length of String:
    int len = str1.length();
    Returns the length of the string.
  • Concatenation:
    String str3 = str1 + " How are you?";
    Using the + operator.
    String str4 = str1.concat(" How are you?");
    Using the concat method.
  • Character Access:
    char c = str1.charAt(0);
    Returns the character at the specified index.
  • Substring:
    String sub = str1.substring(7);
    Returns a substring from index 7 to the end.
    String sub2 = str1.substring(7, 12);
    Returns a substring from index 7 to 11.
  • String Comparison:
    boolean equals = str1.equals(str2);
    Compares strings for equality.
    boolean equalsIgnoreCase = str1.equalsIgnoreCase("hello, world!");
    Ignores case.
    int cmp = str1.compareTo(str2);
    Lexicographically compares two strings.
  • String Search:
    int index = str1.indexOf("World");
    Returns the index of the first occurrence of "World".
    int lastIndex = str1.lastIndexOf('o');
    Returns the last occurrence of 'o'.
  • String Replace:
    String replaced = str1.replace("World", "Java");
    Replaces "World" with "Java".
  • Trim:
    String trimmed = str1.trim();
    Removes leading and trailing whitespace.
  • Split:
    String[] parts = str1.split(",");
    Splits the string into an array based on the delimiter.
  • Convert to Upper or Lower Case:
    String upper = str1.toUpperCase();
    Converts the string to uppercase.
    String lower = str1.toLowerCase();
    Converts the string to lowercase.

4. StringBuffer and StringBuilder

For scenarios requiring frequent modification of strings, Java provides StringBuffer and StringBuilder classes:

  • StringBuffer:
    Mutable sequence of characters, thread-safe.
    StringBuffer sb = new StringBuffer("Hello");
    sb.append(" World!");
    Modifies the same object.
  • StringBuilder:
    Similar to StringBuffer, but not thread-safe (faster in single-threaded environments).
    StringBuilder sb = new StringBuilder("Hello");
    sb.append(" World!");
    Modifies the same object.

5. String Conversion

Strings can be easily converted to other data types and vice versa:

  • String to Primitive Types:
    int num = Integer.parseInt("123");
    double d = Double.parseDouble("3.14");
  • Primitive Types to String:
    String str = String.valueOf(123);
    String str2 = Integer.toString(456);

6. String Interning

The intern() method can be used to return a canonical representation of the string, ensuring that all equal strings share the same memory reference.

String interned = str1.intern();

7. String Formatting

Java provides a String.format() method to create formatted strings:

String formatted = String.format("Hello, %s! You are %d years old.", "John", 25);

Lecturre learning image

8. Checking if a String is Empty

boolean isEmpty = str1.isEmpty();

Checks if the string is empty.

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?