its is called every time you add an element to TreeSet. Since treeset by default does the sorting on the basis of comparator implemented for the class. In this case Student is object and the Student class is implementing comparator interface.
Well the compareTo method will actually be called only when add method is called on a TreeSet which has any elements. If there are no elements in the TreeSet, then the method will not be called on adding an element .
And as far as the type casting goes, you have to do that only because you didn't use generics. If you use this syntax for your declaration
Then you don't need any type casts and you can use the enhanced for loop like this