Why do we use static block ????

my question is that why do we use static block for certain statements and declarations ?? what advantage do they hold???
Please help me........

Here is an example:
If you use a JDBC-driver, it's enough to write:
   String driverName = "package.MyDriver";
   Class.forName(driverName);In the class "MyDriver" there is a static block:
public class MyDriver implements java.sql.Driver {
   static {
      MyDriver driver = new MyDriver();
      java.sql.DriverManager.registerDriver(driver);
}

Similar Messages

  • Why not to use static methods - with example

    Hi Everyone,
    I'd like to continue the below thread about "why not to use static methods"
    Why not to use static methods
    with a concrete example.
    In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
         public static void wait(int millis){
              r.delay(millis);
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
    Thanks for any comments in advance,
    lemonboston

    maheshguruswamy wrote:
    lemonboston wrote:
    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
    Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
    To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
    If you use a Singleton (and and interface), you can do something like this:
    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
    There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
    And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class.

  • Why not to use static methods in interfaces?

    why?

    Because static methods are always attached to a particular class -- not an object. So object polymorphism (which is what interfaces are good for) won't help. Now, what you can do is say that subclasses must implement a method that looks an awful lot like a static method, in that it doesn't depend on object state.
    This bugged me, and it still bugs me a little bit in that I have to instantiate an object of a type in order to call these pseudo-static methods. When the pseudo-static methods tell the user how to initialize the object, you get a bit of a chicken-and-egg problem.

  • Use of functions in static block

    Hello,
    I have this app containing a static {} block. The reason it's there is to 1) provide a splash screen 2) have input dialog to process input string and check if it's valid in order to load app or not.
    In pseudocode it's like this:
    1 - get input string with showInputDialog()
    2 - check for the input string validity (a valid string is with prefix A-, C- or S-)
    3 - if string is valid, load the app
    4 - if string is not valid, proceed to step 1.
    As you may already see, there is going to be a lot of code (with if-else statements) to check for A-, C- and S- prefixed because I am using indexOf() function which takes only one parameter.
    I am considering a way to somehow check recursively, but for this I think I'll need a function to call indexOf() with A-, C-, S- and assess validity for each case.
    My question is, is there a way in the static block to have a function? Or can somebody please recommend an efficient approach to checking a string validity with different possibilities inside a static block as in my case, to avoid lots of if-else statements?
    P.S. My apologies for initially posting this thread in wrong section.
    Thank you!
    Victor.

    DrClap wrote:
    What's a function? And why are you particularly concerned about doing those things in a static initializer as opposed to in some other place?Hi,
    Sorry, I'm still thinking c++. I meant method. Something like of the form:
    static
    boolean valid = false;
    while string is not valid
    stringfrominput = showInputDialog();   
    //determine if string is valid
    valid = checkvalid(stringfrominput)
    //if possible to have
    boolean checkvalid(stringfrominput)
    recursively process stringfrom input based on A-, S-, or C- prefixes
    return boolean value
    }I have a jar app. It is Windows-based and runs as a TrayIcon application. If I include this process when class is loaded, this means that the app will be loaded with all its features. But I need to make sure that the app's features will be loaded only if certain conditions are met.
    I am not sure how else to approach this requirement without using static {} block.
    Thank you,
    Victor.

  • Help required in understanding of static blocks in java

    Hi ,
    Can some one help me in understanding the difference between static blocks in java....also what is the difference in declaring some static variables in a class and and declaring some variables in a static block? From an architecture viewpoint when should one use static blocks in Java?

    Static blocks are piece of code that can beexecuted
    before creating an instance of a class.static blocks are executed once, when the class
    itself is loaded by the JVM. They are not executed
    before creating each instance of a class.
    For example whatever you include in the mainn method will be
    executed without you having to create the instanceof
    the class using the new operator. So you can saythe
    main method is a static block.main is not a static initialisation block but a
    static method. a special case static method at that -
    it is only executed when the containing class is
    specified as a parameter to the JVM. (unless you
    specifcally call it elsewhere in code - but that
    would be bad form).
    in answer to the original post, static variables
    belong to the class. each instance of the class share
    the same static variables. Public static vars can be
    accessed by prefixing them with the class name. A
    static initialisation block can be used to
    initialise static variables. Variables declared
    within the static initialisation block exist only
    within the scope of the block.
    e.g.
    public class Foo {
    static Bar bar;        // static member variable
    // static initialisation block
    static {
    // variable declared in static block...
    String barInfo =
    arInfo = System.getParameter("barInfo");
    // ... used to initialise the static var
    bar = new Bar(barInfo);
    So is the only purpose of static initialization blocks is to initialize static variables? Does the initialization of static variables inside a static block make any difference in performance? If yes , then how ?

  • Why use finally block

    why use finnaly block when we can close the resources after the try cath method has executed

    The real reason is that you don't usually catch all exceptions (and you shouldn't). The code shown doesn't catch Errors for example, yet you would always want the resources allocated in the method to be released regardless of any exceptions that are thrown, not just the ones you catch yourself.

  • Why a static nested class instead of a static block?

    What difference does it make: using a static nested class on a static block?

    Surya-2010 wrote:
    What difference does it make: using a static nested class on a static block?Do you mean static initialization block?
    They're different concepts. A static initialization block is part of the construction machinery of a class. A static nested class is a class you want to treat as part of another class.

  • Why can't I use static IP anymore?

    I just set up a new intel Mini as part of my media center. I want to do like the other Macs on my network -- use static IP addresses and port forwarding to allow vnc connections.
    I'm connected via ethernet. I get dhcp just fine. But when I take the dhcp address, or, for that matter, the next static IP in line, I lose all connectivity to the internet. I've verified that my dns settings are correct.
    This is driving me crazy. For example, 192.168.1.106 is what it grabs from dhcp, and it works just fine. If I switch to manual and set if for the exact same thing, it goes offline and won't come back until I switch it back to dhcp.
    Any ideas? I've got an XP box and two G5's (Tiger) all configured with staticIP/port forwarding, and they work just fine.
    Thanks.

    Don't forget that there are many "pieces" to internet access that must all be set to make manual IP selection work, namely:
    1) Your IP address
    2) The addresses of your DNS servers
    3) The default route via which packets leave your network ("router" in Network->TCP/IP)
    4) Your subnet mask
    As mentioned above you also need to assign an address from outside the DHCP pool that is on the same subnet, as at least some routers will refuse to route traffic that seems to originate from IP addresses that fall within the DHCP pool over which it has control if it did not yet assign that IP address to a client.

  • Why is User defined exception block not reaching

    I want to catch exception if wrong column name is there in a select statement.
    In this example i am useing static query but in real time it will be a dynamic query and it may be possible that a particualre column has been deleted from that table so an error will be returned that we need to catch and display custom message to the user. But control is not going to exception block.
    type_id1 column is not there in table1
    what is that i am missing here?
    declare
    vcTypeID varchar2(10);
    invalid_COLUMNs EXCEPTION;
    pragma exception_init(invalid_COLUMNs,-06550);
    begin
    select to_char(type_id1) into vcTypeID from table1 WHERE ROWNUM=1;
    dbms_output.put_line(vcTypeID);
    exception
    when invalid_COLUMNs then
    dbms_output.put_line('def');
    when others then
    dbms_output.put_line('others');
    end;
    Edited by: user13065317 on Jun 1, 2012 12:47 AM

    Hi,
    Why are you trying to catch 6550? I'd rather try with 904 - invalid identifier
      1  DECLARE
      2  e EXCEPTION;
      3  PRAGMA EXCEPTION_INIT(e, -904);
      4  v VARCHAR2(128);
      5  BEGIN
      6   EXECUTE IMMEDIATE 'SELECT TO_CHAR(nonexisting) FROM dual' INTO v;
      7  EXCEPTION
      8   WHEN e THEN dbms_output.put_line('Invalid identifier');
      9* END;
    SQL> /
    Invalid identifier
    PL/SQL procedure successfully completed.
    SQL>Lukasz

  • Can I use static variable in EJB?

    Many books suggest developer don't use static variable in EJB,I want to know why?
    I know there isn't any problem if the static varibale is read only
    For writable static varible ,what will happen if I use a static Hashtable for share data
    Help me!Thank you very much!!

    Greetings,
    I know that "EJB business methods are not allowed to
    block on synchronized resources" Just where do you "know" that from?? The EJB 2.0 Specification, at least, is nowhere in agrement with this statement. If it comes from a book I would question the author's reasoning. Contractually, there's no sound basis for this. In the case of Session Beans, they have an expressedly direct and single-threaded association with a client. From a design viewpoint, it certainly seems unnecessary for a bean to "block" its one-and-only client, but to say that it "is not allowed to" do so is without merit. Entity Beans, on the other hand, are concurrently accessible. Yet, with regard to a transactional context being in effect, the container does indeed block on a bean's business methods. For the bean to do so itself is, therefore, unnecessary. Furthermore, the specification explicitly concedes that a "Bean Provider is typically an application domain expert" and "is not required to be an expert at system-level programming." (EJB 2.0 Spec. 3.1.1) From these statements alone it is reasonable to assume the above statement is meritless since the Bean Provider is not expected to even consider synchronization issues when developing a bean.
    But I'm mixed up why we could use "Hashtable" or otherApparently, because your sources are as well...
    collection classes in the EJB ,in these method many
    methods are synchronized In fact, not only "can we use" them but, with respect to multiple-row finders in Entity Beans we are [i]required to use them (or an iteration of them)! Not all Collection classes are synchronized (so called "heavy-weight collections"). As shown above, that the choice of a particular Collection class might be synchronized is of little consequence since a bean designed under strict adherence to the specification ensures that it is never concurrently writeable.
    Could someone provide a good way for this problem?
    Please Help Me!!!Regards,
    Tony "Vee Schade" Cook

  • Exception in static block + re-instantiating

    Hello All,
    I have got a number of unit tests and one that is running is causing an exception in a static block of a class which is expected. It throws an ExceptionInInitializerError which I catch in the unit test.
    But then another test is running using the same class and this time it should pass and create an instance of the same class as before.
    But instead I receive a java.lang.NoClassDefFoundError with no class name. Why? Can't I instantiate a class again once the initialisation had failed?
    Regards
    Jonas

    It's part of the VM Specification.
    See [2.17.5 Detailed Initialization Procedure|http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#24237]
    The first time,
    10. Otherwise, the initializers must have completed abruptly by throwing some exception E. If the class of E is not Error or one of its subclasses, then create a new instance of the class ExceptionInInitializerError, with E as the argument, and use this object in place of E in the following step. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead use an OutOfMemoryError object in place of E in the following step.After that,
    5. If the Class object is in an erroneous state, then initialization is not possible. Release the lock on the Class object and throw a NoClassDefFoundError.

  • [Problem reading a file in a static block of code]

    Hi all,
    I'm trying to use a static block of code in an abstract class (let's say for initialisation). In this block I'm trying to read some lines of text from a file, and some FileNotFoundException are thrown,
    java.io.FileNotFoundException: file:/home/tom/workspace/cryptanalysis/data/keys (No such file or directory)
    java.io.FileNotFoundException: file:/home/tom/workspace/cryptanalysis/data/french_words (No such file or directory)
    but all the paths are valid and the files exist as you can see:
    tom@javahouse ~ $ ll /home/tom/workspace/cryptanalysis/data/
    total 24K
    -rw-r--r-- 1 tom users 151 jan 3 23:26 french_frequences
    -rw-r--r-- 1 tom users 2,0K jan 4 17:21 french_texts
    -rw-r--r-- 1 tom users 11K jan 4 17:16 french_words
    -rw-r--r-- 1 tom users 159 jan 4 17:21 keys
    tom@javahouse ~ $ cat /home/tom/workspace/cryptanalysis/data/french_words
    LE
    DE
    UN
    ETRE
    ET
    A
    IL
    AVOIR
    NE
    JE
    SON
    QUE
    SE
    QUI
    CE
    DANS
    I really don't understand why those exceptions are thrown, if somebody
    could help it would be very nice. (It is for a crypto school project)
    Thanks in advance. (Sorry for my english 'cause I'm french)
    Here is a code snippet :
    // Path to this class:
    // /home/tom/workspace/cryptanalysis/utils/TextUtils.java
    public abstract class TextUtils {
         private static String PATH;
         public static String[] KEYS;
         public static String[] WORDS;
         public static String[] PLAINTEXTS;
         public static float[] FREQUENCES;
          * Init KEYS, WORDS, PLAINTEXTS, FREQUENCES, and PATH,
          * with the files in the data folder.
         static {
              String line;
              PATH = TextUtils.class.getResource("../data/").toString();
              System.out.println(PATH);
              // When PATH is printed, it looks like this /home/tom/workspace/cryptanalysis/data/
              KEYS = FileUtils.readFileContent(PATH + "keys"); // Here is the first exception
              WORDS = FileUtils.readFileContent(PATH + "french_words");// Here is the second
              PLAINTEXTS = FileUtils.readFileContent(PATH + "french_texts");// Here is the third
              FREQUENCES = new float['['];
              try {
                   BufferedReader reader = new BufferedReader(new FileReader(PATH + "french_frequences"));// And the fourth
                   while(null != (line = reader.readLine()))
                        FREQUENCES[line.charAt(0)] += Float.parseFloat(line.substring(1));
              } catch (Exception e) {e.printStackTrace();}
    // Path to this class:
    // /home/tom/workspace/cryptanalysis/utils/FileUtils.java
    public abstract class FileUtils {
          * Read the content of the file denoted by the given path and
          * return an array of Strings containing each line.
          * @param path
          * @return an array containing all the lines from the file
         public static String[] readFileContent(String path) {
              try {
                   String line;
                   Vector container = new Vector(100, 100);
                   System.out.println(path);
                   BufferedReader reader = new BufferedReader(new FileReader(path));
                   while(null != (line = reader.readLine()))
                        container.add(line);
                   return (String[])container.toArray(new String[container.size()]);
              }catch(Exception e) {e.printStackTrace();return null;}
         ....

    vous �tes le type bienvenu
    (thats bablefish for "you're welcome dude")Wow! That means "vous �tes bienvenu" means "You are welcome here" (i.e., "welcome at the forum", or whatever), not the proper answer to "Thank you".
    The shortest form of "You're welcome" in the sense you intended it is "De rien". [literally, "of nothing"--so it would be something like if you said in English, "It was nothing."]

  • Using Static Variable against Context Attribute for Holding IWDView

    Dear Friends,
    I have a method which is in another DC which has a parameter of the type IWDView. In my view, I will have an action which will call the method in another component by passing the value for the view parameter. Here, I can achieve this in 2 types. One is - I declare a static variable and assign the wdDoModifyView's view as parameter value and I can pass this variable as parameter whenever calling that method or the second way - create an attribute and assign the same wdDoModifyView's view parameter as its value. Whenever I call this method, I can pass this attribute as parameter. What is the difference between these two types of holding the value since I am storing the same value i.e., wdDoModifyView's view parameter. But when I trigger the action from different user sessions, the first type of code (using static variable) prints the same value in both the sessions for view.hashCode() and View.toString(), but the same is printing the different values when I pass the attribute which holds the view parameter.
    Clarification on this is highly appreciated
    The problem I face is when I use static variable to get the view instance and export the data using the UI element's id, the data belonging to different user sessions is mixed up where as when I use Context Attribute, the same problem doesn't arise. I want to know the reason why it is so. Is there any other place or way where I can get the current view instance of each session instead of wdDoModifyView?

    Hi Sujai ,
    As you have specified the problem that we face when we use  static attributes, when end users are using the application .
    Static means i  have n number of objects but the static variable value will remain same every where.
    when it is context attribute for every object i.e nth object you have a nth context attribute i mean nth copy of the context attribute.
    so every user has a unique Iview parameter , when context is used and
    when static is used  , assume you have userA , his iview is set this intially  and u have another user B , when he is using  , since the variable is static and when you access this variable you will get the value of userA.
    Regards
    Govardan Raj

  • I have time capsule and I am unable to connect to the internet using static public IP

    I have been using my Time Capsule on my company network for some time.
    Recently I removed the time capsule and connected the TC  Wan port directly to the firewall.  We have got block of static IPs provided to us from our ISP.
    Im confused in filling up the internet tap on the Airport Utility (Lion Version)
    If Im using a static public IP to connect to the internet should I use
    Static, DHCP or PPoe?
    IP Address: is this the IP address of the public IP address given to Us from ISP?
    Subnetmask. ..no problem
    Router Address: what should I type here: IP address of my firewall or my ISP's GateWay IP?
    DNS servrs are clear...
    Please guide me.

    Normally you would just set this up with dhcp to the firewall.. if the firewall is setup correctly it will simply pass you one of the block of static IP addresses.. if it doesn't or get a NAT address you should be able to allocate a static IP to the TC in the firewall to its MAC address.
    I am not sure that the static IP will work if you just type it in.
    If you want to have a go..
    If Im using a static public IP to connect to the internet should I use
    Static, DHCP or PPoe?
    Try static only if dhcp doesn't work because the firewall is not setup.
    IP Address: is this the IP address of the public IP address given to Us from ISP?
    Yes, a free IP from the block.
    Router Address: what should I type here: IP address of my firewall or my ISP's GateWay IP?
    Either should work if the firewall is setup correctly.. otherwise just try ISP gateway.

  • Can we have try/catch in a static block in a class?

    hi All
    i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.

    You could just swallow the exception inside try/catch
    block, and instead of throwing it out, just set a
    static variable to allow checking from outside
    whether the initialization succeeded, or check within
    the constructor / methods of this class for
    successful initialization, and throw the exception
    then. You could even save that exception in a static
    variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be.

Maybe you are looking for

  • Can't remove Core Storage from hard drive

    I wanted to erase a backup drive and start over again but somehow it's gotten converted to "Core Storage" I'm told. I managed to erase the drive by first listing the Core Storage devices, using the following command in the OSX Terminal: diskutil cs l

  • Is there a way to customize the IDE font?

    Hi, I'm trying to tweak the JDeveloper IDE so that I could specify the font for the menus and dialogs, which seems to be the default 'sans-serif'; I know, it's the least annoyance you can have, but, however, if there's a way to do it plz let me know.

  • Printing or Exporting Detail View

    I am unable to export a Detail View sheet to PDF, as it separates the two columns onto two pages instead of printing them together on the same sheet as it shows in the preview. After a couple of hours speaking with tech support, they were unable to r

  • Starting iphone4

    When I started my iphone, it asked for language then country,and the asked to connect through wifi or itunes when connected through itunes it is error message UNABLE TO CONNECT NOW KINDLY CONTACT CUSTOMER CARE. Kinly look into the matter on priority

  • Making Custom Template in DVDSP

    I have a DVD set up with two menus, connections, and a script. When I try to save it as a custom template it will only save a single menu and track. Is it not possible to save a custom template with multiple assets? (menus, track place holders, and s