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";
→ 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");
→ 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
- length() → get string size.
- charAt(int) → access character at position.
- substring(int, int) → extract part of string.
- equals() → compare string values.
- equalsIgnoreCase() → case-insensitive comparison.
- compareTo() → lexicographic comparison (ASCII values).
- toUpperCase()/ toLowerCase() → case conversion.
- trim() → removes leading and trailing spaces.
- replace(old, new) → replace characters (literal).
- replaceAll(regex, replacement) → regex-based replacement.
- split(String regex) → split string into array.
- contains(CharSequence) → check substring.
- startsWith() / endsWith() → check prefix/suffix.
- intern() → returns string from string pool.
Top comments (0)