Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Static block' - 4 code snippet(s) found

 Sample 1. Declaring static block

public abstract class TestClass {
static{
init();
}

public static void main(String[] args){
}

private init(){
}
}

   Like      Feedback     static block  abstract class declaration


 Sample 2. Singleton Class ( using private constructor , object initialization using static method, doubly checked , thread safe, synchronized , volatile reference )

class Singleton {
   private static volatile Singleton instance = null;
   private Singleton(){}
   public static Singleton getInstance() {
      if (instance == null) {
         synchronized(Singleton.class) {
            if (instance== null)
               instance = new Singleton();
            }
         }
      return instance;
   }
}

   Like      Feedback     singleton   singleton class   volatile   private constructor    object initialization using static method   doubly checked    thread safe   synchronized block using class level lock   synchronized   synchronized block   class level lock


 Sample 3. Initialize maps through static block

public class CoinChanger {
   private static Map<Currency, Integer> cashBox;
   private static Map<Currency, Integer> change;

enum Currency {
      DOLLAR,QUARTER,DIME,NICKEL,PENNY;
   }

   static {
      cashBox = new TreeMap<Currency, Integer>();
      change = new TreeMap<Currency, Integer>();
      initializeCashBox();
   }

   private static void initializeCashBox(){
      //set the cash box
      cashBox.put(Currency.DOLLAR, 50);
      cashBox.put(Currency.QUARTER, 0);
      cashBox.put(Currency.DIME, 50);
      cashBox.put(Currency.NICKEL, 50);
      cashBox.put(Currency.PENNY, 50);
   }
}
}

   Like      Feedback     static block   enum   initializing maps   initializing treemap


 Sample 4. Usage of Static Block and Instance Initialization Block

public class BuggyBread { 

   static {
      System.out.println("Static Block");
   }

   {
      System.out.println("Instance Initialization Block");
   }

   BuggyBread(){
      System.out.println("Constructor");
   }

   public static void main(String[] args){
      System.out.println("Main Method");
      new BuggyBread();
   }
}

   Like      Feedback     static block   Instance Initialization Block



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus