Junior
What do you know about the String class in Java?
sobes.tech AI
Answer from AI
String in Java is an immutable class representing a sequence of characters.
Key features:
- Immutability: Once a String object is created, its contents cannot be changed. Any operation that appears to modify the string actually returns a new String object. This makes String objects thread-safe.
- String Pool: Java maintains a pool of String literals. When a string literal is created (e.g., "hello"), JVM first checks the pool. If such a string already exists, a reference to the existing object is returned. If not, a new object is created in the pool. Using the constructor
new String("hello")always creates a new object outside the pool. - Operator
+Overloading: The+operator is overloaded for string concatenation. The compiler can optimize concatenation using StringBuilder or StringBuffer for better performance. - Interface Implementations:
StringimplementsSerializable,Comparable<String>, andCharSequence. - Methods: The String class provides many useful methods such as
length(),charAt(),substring(),indexOf(),equals(),equalsIgnoreCase(),startsWith(),endsWith(),trim(),replace(),split(), and others.
Examples of creating strings:
// Creation via literal (uses string pool)
String str1 = "Hello";
// Creation via constructor (creates a new object outside the pool)
String str2 = new String("World");
// Creation from a character array
char[] chars = {'J', 'a', 'v', 'a'};
String str3 = new String(chars);
String comparison:
equals(): Compares string contents.==: Compares references. For string literals with the same content, it usually means the same reference from the pool, but for objects created withnew String(),==isfalseeven if contents are the same.
String s1 = "java";
String s2 = "java";
String s3 = new String("java");
System.out.println(s1 == s2); // true (both from pool)
System.out.println(s1 == s3); // false (s3 is a new object)
System.out.println(s1.equals(s3)); // true (compares contents)
To modify strings in Java, classes StringBuilder (not synchronized, for single-threaded environments) and StringBuffer (synchronized, for multi-threaded environments) are used, which are mutable.
// Example with StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
String result = sb.toString(); // Convert back to String
System.out.println(result); // Output: Hello World