Member-only story

Java Concepts That Look Similar but Work Differently

Rishi
3 min read6 days ago

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 a try-catch block.
  • finalize → A method in Object class, called by the Garbage Collector before reclaiming an object’s memory.

Example:

class FinalExample {
final int x = 10;

void test() {
// x = 20; //…

--

--

Rishi
Rishi

Written by Rishi

Tech professional specializing in Java development and caching logic with expertise in SaaS and automation. https://rishi-preethamm.blogspot.com

No responses yet