Monday, August 10, 2015

Defining Map to maintain counter on key basis


Most of the time if we have to maintain a counter on key basis then we define a map as follows
Map<String, Integer> map = new HashMap<String, Integer>();
Do we have any problem with the above statement???
Yes, the problem is with value but what's the problem with Integer as a value?
We have defined Integer object as a value and Integer is an immutable class so whenever we perform operation on the value (increment or decrement) a new Integer object will be created this is where the problem lines in, after increment/decrement n number of time we might have created n number of objects.
So whats the solution for the above problem
1) A very simple solution is to define a bean and take primitive int/long/double (whatever datatype you want) and based on the key increment/decrement the values in the bean object and provide getters to get the Count.
2) We can use AtomicInteger because its mutable.
Keep exploring Java smile emoticon
Now a days, a very simple but tricky question "How to Prevent Method Overriding in Java" is asked in interview.
Many of us just answer that final keyword is used to prevent overriding but there are 2 more ways to prevent overriding.
1. final
2. private
3. static
Generally, we answered only first one i.e. final keyword but make sure to answer properly (mentioned all 3 ways) to impress interviewer. Interviewer knows that all are familiar with final and they ask this question to know whether you know about other 2 ways or not.
So, don't take this question easily and make sure to explain all three, if this question is asked in interview.
Keep exploring Java.
Why are all OS built by C, C++ etc.? Why not Java?

Because Java itself requires JVM to ensure platform independence. So, lets assume you code an OS using Java. Now, if you start thinking recursively, your OS requires JVM to run, JVM requires OS, OS requires JVM, JVM requires OS.. infinite mutual recursion.
System Stack Overflow! grin emoticon
On a serious note, Java is just not designed for system programming. C is more effective when you require direct interaction with the hardware and memory but Java doesn't allow interaction with hardware/memory. You will understand it even better if you get your hands dirty on some system programming with C/C++.
Even, OS can't be built 100% in Java but it can be built with the mixture of Java and C/C++. Just write some part of OS in C/C++ that would be sufficient to start the JVM then rest of the OS could be written in Java.
Examples of attempts at such an operating system include JavaOS, JOS,[2] JNode, and JX.