Wake Me Up When The Interview Ends: The Agony of Java Backend's Memorization Game
The Price of Admission: Why We Must Master the Java Backend's Standardized Answers😥
seal
Basic Java
Differences in Usage between == and equals
First of all, ==
is an operator, and equals
is a method.
==
Compare the values of variables to see if they are same.
- If the objects being compared are of Basic data type, the comparison is done to see if the values are the same.
- If the objects are of Reference data type, the comparison is done by address.
equals
Compare the values of objects to see if they are same.
Equals method exists in the Object class:
public boolean equals(Object obj) {
return (this == obj);
}
So when this method isn't overridden, it "equals" to the ==
in fact. But you can override this method to change it's logic.
Differences between String, StringBuffer and StringBuilder
Items | String | StringBuffer | StringBuilder |
---|---|---|---|
Mutability | Immutable. The core of the String class is a char[] array named value , which is modified with the final keyword (the array reference cannot be changed) and has no external modification entry (no setter or expansion method). Each operation (e.g., + , substring ) generates a new String object. |
Mutable. StringBuffer inherits from AbstractStringBuilder (the parent class is not modified with final ), so it can directly modify the internal char[] array without creating new objects. |
Same as StringBuffer (inherits from AbstractStringBuilder and supports direct modification of the internal char[] array, no new objects created). |
Thread Safety | Thread-safe. Since the internal value array cannot be modified, concurrent access will not cause data confusion. |
Thread-safe. All modification methods (e.g., append() , insert() ) are modified with the synchronized keyword, ensuring only one thread can execute the method at a time. See Note 1 for details. |
Not thread-safe. It has the same mutable features as StringBuffer but lacks synchronized modification—concurrent modification may cause data errors (e.g., index out of bounds, character overwriting). See Note 2 for details. |
📕Note 1
public synchronized StringBuffer append(String str)
public synchronized StringBuffer insert(int offset, String str)
public synchronized StringBuffer delete(int start, int end)
you can see thatsynchronized
is used extensively here, it is a kind of Pessimistic locking, Unfair locking, Reentrant locking and Exclusive locking.
This ensure Thread safety.
📕Note 2
Faster because no locks are used