Wednesday, March 20, 2013

Java Confusions

1) Why static block?

Java static blocks are used to initialize the static variables. The static block code is loaded when Java Virtual Machine(JVM) loads the class.  Since we know, static variables can not be included in constructor, only member variables can be initialized in constructor. So, for static variables, the static blocks work like a constructor. We can have any number of static blocks that are executed at the time class is loaded. See the example below:

class MyClass { 
 static Map labels = new HashMap(); 
 static { labels.put(5.5, "five and a half"); 
 labels.put(7.1, "seven point 1"); } 

2) Why final keyword for classes, variables or arguments

Please have a look at my previous article which clarified in somehow more detail:
Final keyword always confusing! 

(TO be continued...)

No comments:

Post a Comment