Java Strings
A String
variable contains a collection of characters surrounded by double quotes.
Creation
In Java, there are several ways to create and manage strings, depending on your use case. Here's a detailed overview of the most important:
1. Using String Literals (Recommended for Simplicity and Efficiency)
Best Use Case: When you need to create immutable and reusable strings.
Example:
String str = "Hello, World!";
Why: Strings created this way are stored in the String Pool, and Java reuses the same object for identical string literals, reducing memory overhead.
2. Using the new
Keyword (Avoid When Possible)
Best Use Case: When you explicitly want to create a new string object.
Example:
String str = new String("Hello, World!");
Why: This creates a new string object in the heap, even if an equivalent string exists in the String Pool, which can be less memory efficient.
3. Using StringBuilder
(For Mutable Strings)
Best Use Case: When you need to modify or concatenate strings efficiently in a single-threaded environment.
Example:
StringBuilder sb = new StringBuilder("Hello"); sb.append(", World!"); System.out.println(sb.toString());
Why: It is faster for repeated modifications because it doesn't create a new string object each time.
4. Using StringBuffer
(For Thread-Safe Mutable Strings)
Best Use Case: When you need mutable strings and thread safety is a requirement.
Example:
StringBuffer sb = new StringBuffer("Hello"); sb.append(", World!"); System.out.println(sb.toString());
Why: Similar to
StringBuilder
but synchronized, which makes it thread-safe (slower thanStringBuilder
in single-threaded use cases).
Comparison
When comparing strings in Java, using the equals()
method is recommended instead of the ==
operator because of how strings are handled in memory. Here’s why:
1. equals()
Method Explanation:
The
equals()
method is used to compare the contents (values) of two strings.It checks whether the characters inside the strings are the same and returns
true
if they are equal.String str1 = new String("hello"); String str2 = new String("hello"); System.out.println(str1.equals(str2)); // true to different objects
2. Difference Between equals()
and ==
:
==
compares object references rather than content.When you use==
with objects (including strings), it checks if the references (memory addresses) of the two objects are the same, not their content.String str1 = new String("hello"); String str2 = new String("hello"); System.out.println(str1 == str2); // false, because str1 and str2 refer to different objects
3. String Pool Optimization:
In Java, string literals are interned. This means that string literals with the same content are stored as a single instance in a special memory pool called the string pool.
String str1 = "hello"; String str2 = "hello"; System.out.println(str1 == str2); // true, because both point to the same literal in the string pool
However, this behavior can be unpredictable when strings are created dynamically (e.g., using
new String()
, concatenation, or reading user input), makingequals()
the safer and more consistent choice.
When to Use equals()
:
Always use
equals()
for comparing string values to ensure content-based comparisons.Using
equals()
makes your code reliable across different string creation scenarios and prevents unexpected behavior due to object reference comparison with==
.
Example Case from Your Code:
In your code example:
if (name.equals("John")) {
System.out.println("Name is John");
}
Here,
equals()
checks if the content ofname
is equal to"John"
.If you used
==
instead, it would only returntrue
ifname
and"John"
refer to the exact same object in memory, which is less reliable.
Good Practice Tip:
To avoid potential
NullPointerException
, a common technique is to callequals()
on the literal string like this:if ("John".equals(name)) { System.out.println("Name is John"); }
This way, even if
name
isnull
, the code won't throw an exception because callingequals()
on"John"
is always safe.
more here: https://javainterviewprep.hashnode.dev/java-equals-and-hashcode