String
String
In Java, the String class represents a sequence of characters. It's one of the most commonly used
classes in Java, and it's part of the java.lang package, so you don't need to import it explicitly. Strings
are used to store and manipulate text data.
For example, when you concatenate two strings, a new String object is created, and the
original strings remain unchanged.
Example:
String s1 = "Hello";
2.String Pool:
Java optimizes memory usage by storing string literals in a special memory area known as the
String Pool.
When you create a string literal, Java checks the String Pool first. If the string already exists in
the pool, the existing reference is returned; otherwise, the string is added to the pool.
Example:
String s1 = "Hello";
String s2 = "Hello"; // s1 and s2 refer to the same object in the String Pool
3. String Interning:
You can explicitly add a string to the String Pool using the intern() method.
If the string is already in the pool, intern() returns the reference from the pool; otherwise, it
adds the string to the pool and returns the reference.
Example:
b.Using new Keyword: When you create a string using the new keyword, a new object is
created on the heap, and the literal may or may not be placed in the String Pool.
String s2 = new String("Hello"); // New object on the heap
7. String Comparisons:
== vs equals():
1. == checks if two references point to the same object.
2. equals() checks if two strings have the same content.
Example:
String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1 == s2); // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)
Q. What is StringBuilder?
Mutability:
Performance:
Thread Safety:
Use Case:
Ideal for scenarios where you need to perform many modifications to a string, such as
building a string in a loop.
Example:
Q. What is StringBuffer?
Mutability:
Thread Safety:
StringBuffer is thread-safe because its methods are synchronized. This means it can be safely
used in a multi-threaded environment where the same instance might be accessed by
multiple threads.
Performance:
o Example:
Thread Thread-safe
Not thread-safe Thread-safe
Safety (inherently)
Slower than
Slower for Faster for StringBuilder due to
Performance multiple multiple synchronization, but
changes changes faster than String for
multiple changes
Frequent string
Frequent string
Fixed strings, modifications in
modifications in a
Use Case few a single-
multi-threaded
modifications threaded
context
context