Friday, March 6, 2026

Small Interview Tip

🔹 Small Interview Tip

 
Difference between == and .equals() in Java

You can say:

  • == → compares memory address

  • .equals() → compares actual value/content

Example:

String a = "hello";
String b = "hello";

System.out.println(a == b); // may be true
System.out.println(a.equals(b)); // always true

In Java, == does not compare the content of strings.
It compares the memory reference (address) of the objects.

So even if both strings look the same, == will often return false, and your program goes to the else block.

✅ Correct Way

Use .equals() to compare string values.

if(orignal.equals(change)) {
System.out.println(text + " is a palindrome");
} else {
System.out.println(text + " is not a palindrome");
}

✔ Corrected Code

public class Palindrome {

public static void main(String[] args) {

String text = "level";
String reverse = "";

int size = text.length();

for(int i = 0; i < size; i++) {
reverse = text.charAt(i) + reverse;
}

System.out.println("Reverse String " + reverse);
System.out.println("Original String " + text);

String original = text.toUpperCase();
String change = reverse.toUpperCase();

if(original.equals(change)) {
System.out.println(text + " is a palindrome");
} else {
System.out.println(text + " is not a palindrome");
}
}
}

Output

Reverse String level
Original String level
level is a palindrome


No comments:

Post a Comment

If you have any problem please let me know.