When comparing two strings, I was taught that we shouldn\'t use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the fo
==
compares the object references
You can understand it by observing the output in the following code:
public class StringComp{
public static void main(String args[]){
String s = new String("hello");
if(s=="hello"){
System.out.println("Hello Friend");
}else{
System.out.println("No Hello");
}
}
}
This program would print No hello
Because in this code, the variable s
refers to new String Object which in turn refers to String literal "hello" from the String pool.