Tuesday, November 29, 2016

Difference between == and equals method with example

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 to Print HashMap in Java


Hello Guys,

How to Print HashMap is very common and frequently ask question now a days for testing programming skills in Java.

So,lets try to understand the  program given below.


import java.util.HashMap;
import java.util.Set;


public class Test extends Thread{

public static void main(String[] args) {
//Creating HashMap key and value as String.
HashMap<String, String> st = new HashMap<String, String>();
//Putting some key and value in Map

st.put("K1", "V1");
st.put("K2", "V2");
st.put("K3", "V3");
st.put("K4", "V4");
st.put("K5", "V5");

//Now iterate or loop Map by using KeySet method of Map
for(String name: st.keySet()){

String key= name.toString();
//Here we are calling get method of Map class by passing key which is we got from KeySet()
String value= st.get(name).toString();
System.out.println("Key:- "+ key +"value:- "+ value );
}
}
}
note:-
1)KeySet returns set view of the keys contained in map.
2)Changes to map will reflect to set and vice-versa also possible.

Its very simple Program and can be use by beginners who just started learning java and collection.

Any comment or Suggestion is most welcome!


Thanks,
Vikas