DEV Community

Tamilselvan K
Tamilselvan K

Posted on • Edited on

Day-81,82 Strings in Java

What is a String in Java?

  • A String is a sequence of characters.
  • In Java, Strings are objects, not primitive types.
  • The java.lang.String package provides the String class.
  • The String class extends Object.
  • Printing an object → internally calls toString().
  • The String class overrides toString().

Creating Strings

1.Using String literal

   String name = "abc";  
   String name2 = "xyz";  
Enter fullscreen mode Exit fullscreen mode

→ Stored in String pool. If another variable stores the same value, it points to the same object.

2.Using new keyword

   String name = new String("abc");  
Enter fullscreen mode Exit fullscreen mode

→ Creates a new object in heap memory, even if the same value exists in String pool.

Properties of Strings

  • String is immutable
  • If we store another variable with the same value, it points to the same object in String pool.
  • == vs equals()

    • == → compares memory reference.
    • .equals() → compares values (content)

Important String Methods

  1. length() → get string size.
  2. charAt(int) → access character at position.
  3. substring(int, int) → extract part of string.
  4. equals() → compare string values.
  5. equalsIgnoreCase() → case-insensitive comparison.
  6. compareTo() → lexicographic comparison (ASCII values).
  7. toUpperCase()/ toLowerCase() → case conversion.
  8. trim() → removes leading and trailing spaces.
  9. replace(old, new) → replace characters (literal).
  10. replaceAll(regex, replacement) → regex-based replacement.
  11. split(String regex) → split string into array.
  12. contains(CharSequence) → check substring.
  13. startsWith() / endsWith() → check prefix/suffix.
  14. intern() → returns string from string pool.

Top comments (0)