Just want to confirm that shoudn't the Compiler stop us when we were putting int values in map where it was expecting String.
How will compiler know what type of key-value pair you store in a raw Map? Generics gives you type-safety. But you can always widen a typed class to a raw type class. In that case you loose the type-safety. To work around this, compiler just adds a typecheck at runtime when you retrieve data from a typed map/collection. And that is giving the cast exception in this case.
Mixing generic code to non-generic code. populate method overlooks at the type safe Map and adds Integer object to the map (Autoboxing is there). Now come back to main method, there is cast (String)map.get(1)+(String)sam.get(1) to get the concatenated String to be printed. But what is got back from the Map are Integer objects, casting Integer to String causes well known ClassCastException.
Abheshek: Just want to confirm that shoudn't the Compiler stop us when we were putting int values in map where it was expecting String.
What is passed to the populate() method is just a plain Map, non-type safe Map, that asks for <Object,Object>. There is no information regarding type safety of the Map that is defined in the main method as Map<Integer,String>.
So simply int is boxed to Integer wrapper and added to the map.