Member-only story
Java has many features that look similar but behave differently. Understanding these differences is essential for writing efficient and error-free code. This blog will clarify some commonly confused Java concepts.
1. ==
vs .equals()
==
compares memory references (whether two objects are stored in the same memory location)..equals()
compares values (whether two objects contain the same data).
Example:
public class EqualityTest {
public static void main(String[] args) {
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false (different objects in memory)
System.out.println(a.equals(b)); // true (same content)
String c = "hello";
String d = "hello";
System.out.println(c == d); // true (same string pool reference)
}
}
2. final
vs finally
vs finalize
final
→ Used to define constants, prevent method overriding, and prevent inheritance.finally
→ A block that always executes after atry-catch
block.finalize
→ A method inObject
class, called by the Garbage Collector before reclaiming an object’s memory.
Example:
class FinalExample {
final int x = 10;
void test() {
// x = 20; //…