Hello Guys,
How == operator and equals method works in java.
So many people ask this question in Java interview and some also give a little program like mentioned below to explain.
Here,we have example for learning about very basic stuff of Java
You can directly run the below program and can see the output.
public class Test {
public static void main(String[] args) {
String s1= "hi";
String s2= new String("hi");
if(s1==s2)
System.err.println("Ist case: s1==s2:result:- "+"++++" +" hascode of S1:= "+s1.hashCode()+ " S2: "+ s2.hashCode());
System.out.println("Ist case: s1.equals(s2):result:- "+ s1.equals(s2));
s2=s1;
if(s1==s2)
System.err.println("2nd case: s1==s2:result:- "+"_-___"+ "hascode true or false of S1:= "+(s1.hashCode() == s2.hashCode()) );
System.out.println("2nd case: s1.equals(s2):- "+ s1.equals(s2));
}
}
OutPut:-
----------
Ist case: s1.equals(s2):result:- true
2nd case: s1==s2:result:- _-___hascode true or false of S1:= true
2nd case: s1.equals(s2):- true
Any Suggestion and comments are most welcome!
Thanks,
Vikas
How == operator and equals method works in java.
So many people ask this question in Java interview and some also give a little program like mentioned below to explain.
Here,we have example for learning about very basic stuff of Java
You can directly run the below program and can see the output.
public class Test {
public static void main(String[] args) {
String s1= "hi";
String s2= new String("hi");
if(s1==s2)
System.err.println("Ist case: s1==s2:result:- "+"++++" +" hascode of S1:= "+s1.hashCode()+ " S2: "+ s2.hashCode());
System.out.println("Ist case: s1.equals(s2):result:- "+ s1.equals(s2));
s2=s1;
if(s1==s2)
System.err.println("2nd case: s1==s2:result:- "+"_-___"+ "hascode true or false of S1:= "+(s1.hashCode() == s2.hashCode()) );
System.out.println("2nd case: s1.equals(s2):- "+ s1.equals(s2));
}
}
OutPut:-
----------
Ist case: s1.equals(s2):result:- true
2nd case: s1==s2:result:- _-___hascode true or false of S1:= true
2nd case: s1.equals(s2):- true
Any Suggestion and comments are most welcome!
Thanks,
Vikas
No comments:
Post a Comment