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 ?

Similar Messages

  • Help required in understanding the flow of control in working with EJB 3.0

    *1. Can anyone help me in understanding the flow after getting an object of InitialContext in using Stateless/Stateful in EJB 3.0 from client i.e. what we are getting in the step Object ref=jndiContext.lookup("CalculateBean/Remote) .*
    *2. What is the use of INITIAL_CONTEXT_FACTORY*
    *3. PROVIDER_URL*
    *4. Java.naimg.factory.url.pkgs*
    *5. why org.jboss.naming and org.jnp.interfaces separated by semi colon.*
    *6. Why we dont require INITIAL_CONTEXT_FACTORY, PROVIDER_URL and Java.naming.factory.url.pkgs if the client is a web client.*
    Properties p=new Properties();
              p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
              p.put(Context.PROVIDER_URL,"jnp://localhost:1099");
              p.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
              Context jndiContext = new InitialContext(p);
         Object ref = jndiContext.lookup("CalculateBean/Remote");
    Calculate c = (Calculate)ref;
    int sum=c.add(3,4);
    System.out.println(sum);
    Thanx in advance........

    Annotations can also be processed at run time using the core reflection API (java.lang.Class & java.lang.reflect.*), so you might want to explore down that path. I have no idea how JBoss actually does it, but annotation processing at build time and core reflection at runtime are the two most obvious possibilities.
    Bruce

  • Help required in understanding the rationale behind singleton class

    Can anyone help me in understanding singleton classes?why do we need them?Architecturally when should we go for a singleton class?

    answer lies in GoF book.

  • Static block in java

    Suppose I have a class that has a static block in it
    public abstract class A {
        static {
        public A(){
        public void doSomething(){
    }And I have two other class viz Class B and Class C which inherit from class A. In this case will classB and classC each call the static block so that it gets called twice in all or will it be only once between Class B and Class C
    public class B extends A {
        public B(){
    public class C extends A {
        public C(){
    }

    And I have two other class viz Class B and Class C which inherit from class A. In this case will classB and classC each call the static block so that it gets called twice in all or will it be only once between Class B and Class CA static block (or static initializer) is executed only once per class, when the class is initialized. The fact that several other classes subclass the superclass does not imply it has to be reinitialized.

  • Help required with understanding References and finalizers

    Background
    I have an online Application which has been developed over 6 years now. It is a Website CMS and runs 300 simultaneous sites per webserver. For the first time I am experiencing capacity / performance issues. I switched from SUN Java to JROCKIT in 2006 which speeded evertything up by 200% but now I have periods of the day where The memory fills up and I get Swapping which leads to 100% cpu utilization - mainly in I/O. I have upped the RAM in the server as a solution and now I want to see if I can do anything to reduce my memory footprint.
    Specifically : The question
    I have captured stats which I can view in Mission Control and it shows that the number of Weak References increases continuously over a 4 hour period (also the number of Phantom references shows similar behaviour). Therefore I suspect a memory leak - Also I suspect that this is of my own making since I have not realy had to deal with this before. The thing is I cannot clearly see how to proceed and identify what my error is.
    I have spent a couple of weeks reading loads of docs about weak / stong etc.. references but I realy need a bit of help with zeroing in on a starting point. I know that I release objects by setting them to null but I now expect that this is not realy good enough.
    Anyway - before I ramble too long, If there is anyone with relevant experience and a few minutes I would be very gratefull to hear from them.
    Regards
    Jonathan Carter
    Glimworm IT
    Amsterdam

    Hi Jonathan,
    Reference objects and finalizers are a frequent cause of performance issues. The reason is that 1) objects tend to be kept alive longer, leading to an increase in live data and more frequent GC and 2) processing of these objects during GC is expensive, which leads to more time spent in GC, i.e. long pause times.
    There are various ways you can approach your issue. One is to use -Xverbose to see what you find. If you are using JRockit R27.2 or later, run with "-Xverbose:referents" to get a list of all reference objects at every GC. More info:
    http://edocs.bea.com/jrockit/jrdocs/refman/optionX.html#wp1029960
    Note that you can enable verbose logging during runtime through "jrcmd <pid> verbosity set=referents" and later disable it using "jrcmd <pid> verbosity set=referents=warn". No JVM restart required.
    If you send your JRA recordings to jrockit-improve AT bea DOT com, we'll try to take a look at them.
    -- Henrik

  • Help required to understand the concepts for data files in tablespace

    Hi Guys!
    Conceptual understanding for data files.
    A tablespace is having 2 datafiles.
    What once the data files will get full? I know we can create data files but what if there is no space on the server for any additional file to be created?
    Do we require to make the oldest file offline and move outside the environment?
    Thanks

    782790 wrote:
    Hi Guys!
    Conceptual understanding for data files.
    A tablespace is having 2 datafiles.
    What once the data files will get full? I know we can create data files but what if there is no space on the server for any additional file to be created?
    Do we require to make the oldest file offline and move outside the environment?
    ThanksIf the datafiles are full, there is not much that you would get from the "defragmentation" of the datafiles. It would be sort of like this in the start,
    FFFFFFFFFFFFFFFFFFFFFFFFFF
    Then it will be ,
    FFFFFFFUUUUUFFFFFUUUUUU
    So what you are going to get is something like this, (if would be done),
    FFFFFFFFFFFFFUUUUUUUUUU
    So that's how the datafile would like. But that won't give you much of the space anyways still. The option to add a storage must be there with you. The file being offline wont take away the space that it has already allocated. And moreover, doing so, would also impact the access to the data that it would be storing within it.
    HTH
    Aman....

  • Help required in understanding when to use encodeChildren() method

    I am new to Java Server Faces. I am a little bit confused in understanding the uselfulness of encodeChildren() method in renderers? Can any one explain how a datatable component gets rendered?how is it that that row by row processing takes place?

    TableRenderer.encodeChildren() is something you can easily imagine:while(there is the next row) {
      UIData.setRowIndex(++rowIndex);
      write("<tr>");
      while(there is the next column) {
        write("<td>");
        while(there is the next component in the column) {
          nextComponent.encodeBegin();
          nextComponent.encodeChildren();
          nextComponent.encodeEnd();
        write("</td>");
      write("</tr>");
    }

  • Help required to understand the configuration parameteres set in Ora JDBC

    Hello Support,
    Client is connected through Oracle JDBC and folllowing values is assigned in the configuration.
    (FAILOVER=on)(LOAD_BALANCE=off)
    I would like to know what is the meaning of above values please ? specially Load_balance = OFF
    Thanks

    I don't know if this will help or not, but with an executable jar file, the classpath is handled differently. All classes are expected to be contained in the jar and external classpath info is ignored. This may also be true in your case if the files are being accessed in that manner. You could try it out quickly by moving the policy and conf files into the jar and dropping the path info.
    If that works, you can decide whether or not you want it packaged that way.
    If it doesn't work, try unpacking the jar file and running it that way, instead of the executable jar. Again, if that works, you can decide how you want to package your app based on that information.

  • Help required to understand interactive SWF appearance on various browsers and pc's

    I have created an interactive newsletter for global distribution.
    My work machine uses a resolution of 1280 x 1024
    However, my company uses different browsers and laptops globally, as we have approx 150,000 employees.
    The Indesign pages are 1000 x 800 px
    When I sent out a few test files, I received various issues from different people.
    Some using IE6, IE7 and IE8 complained that although their resolutions were 1280 x 800, or 1280 x 1024, the  top and bottom of the swf files were either cut off or the file was presented with text too small to read.
    Using Firefox, some of the people also said that the file presented with the top and bottom cut off.
    My own PC using either IE8 or Firefox @ 1280 x 1024 presents the file perfectly fine.
    Now, with IE 8 and firefox, by either using the CTRL + middle mouse wheel, or CTRL and + or - the SWF file resized correctly by zooming in and out.
    For IE6 the user would need to right click and choose Zoom in or Zoom out.
    Most users are, and I am not being patronising here, not computer savvy, and would not generally know how to perform this option. They simply use the computers to do their job and panic if a java updated is presented.
    I need to avoid this if I am to pursue the interactive SWF file approach.
    Has anyone else experienced this and can you offer a solution that, no matter the resolution ot Browser used the SWF file will present correctly all the time?
    thanks

    The usual approach is to assume the smallest pixel dimension for a desktop is 1024x768, so you set the flash stage at around 900x650. If you are coding in Actionscript there is the option to listen for a browser resize and rearrange the objects on the stage to fit the space, but that's not an option saving out of ID. The best approach is to setup your ID page to 900x650,  and make sure the text is readable at 100% view.

  • Help required in knowing about graphic components in java

    Hi I am in urgent requirement of finding out some graphing components for java.I want these components to work with Jsp. I am new to this and have no idea as to where to search for them. can any one help me in trying to find something.Is there anything like chart fx?

    Please check online help:
    http://developers.sun.com/prodtech/javatools/jscreator/reference/docs/help/2update1/vcs-nb/vcs_cvs.html
    and
    Source Code Control Features in the Sun Java Studio Creator 2 IDE
    http://developers.sun.com/prodtech/javatools/jscreator/reference/fi/2/source-code-control.html

  • Static block

    What are the contexts in which static block is used?
    Plz..I dont need an answer like---Whenever anything need to be executed/initialised before main method, static block is used..
    I need the contexts in which static block are used/would be helpful..
    Regards,
    Anees

    A static block has nothing to do with the main method.
    "static" means: associated with the class itself, rather than individual instances of the class. So a static block can be used to manipulate static variables, or perform other actions when the class is loaded.
    For example, it could be used to fill a static collection of values:public static final Map<String, Country> countries = new HashMap<String, Country>();
    static {
      countries.put("us", new Country("us", "United States of America");
      countries.put("ca", new Country("ca", "Canada");
      // etc...
    }

  • Help needed to understand JLS �15.14

    Can someone please help me to understand JLS �15.14 (http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.14), it says:
    Postfix expressions include uses of the postfix ++ and -- operators. Also, as discussed in �15.8, names are not considered to be primary expressions, but are handled separately in the grammar to avoid certain ambiguities. They become interchangeable only here, at the level of precedence of postfix expressions.
    PostfixExpression:
    Primary
    ExpressionName
    PostIncrementExpression
    PostDecrementExpression
    Questions:
    1. According to documentation above, "Primary" & "ExpressionName" are also considered as "PostfixExpression". Can someone please explain with some grammar examples?
    2. The statement "They become interchangeable only here, at the level of precedence of postfix expressions." What is exactly interchangeable? Where can I find the level of precedence of postfix expressions?
    Thank you for your time.

    Well I wouldn't consider myself any expert in language grammars and thus I don't really want to take any position considering this spec. Even though I know how to use the ++ and -- operators, this kind of documentation always remains cryptic :)

  • Help required understanding the purpose of having instance Init blocks

    I want to know exactly what the purpose of having instance initialization blocks in Java. As in static init blocks, we can execute some commands before creating an instance of a class.
    And also in instance init blocks, we are executing some commands which we can do in a constructor. So I’m little bit confused of the purpose of having this concept instance init blocks without writing it in the constructor itself.
    Really appreciate if anyone can explain this ASAP as I am still a beginner who is studying for SCJP exam.
    Thanks in advance.

    The instance initialization blocks are always executed before the constructor code is executed. This may be used for some activity which is common to all constructors (in case constructors are overloaded).

  • Help required on java.lang.StackOverFlowError and static initializer

    I wanted to create an instance of a class that contains another instance of the same class. So I wrote:
    class A {
         A z = new A ();     
         void display () {
              System.out.println ("Hello World");
         public static void main (String [] args) {
              A y = new A();
              y.display ();
    }During execution I got java.lang.StackOverFlowError. But if I put a static initializer, it works fine. Here is the code using static initializer.
    class A {
         static{
              A z = new A ();     
         void display () {
              System.out.println ("Hello World");
         public static void main (String [] args) {
              A y = new A();
              y.display ();
    }Could anyone please help me to understand the logic why "java.lang.StackOverFlowError" is happening here and how the same program runs fine by putting a static initializer ?
    Regards,
    Shambhu

    Could anyone please help me to understand the logic
    why "java.lang.StackOverFlowError" is happening hereWhen you instantiate an A object with A y = new A () then A z = new A () also gets executed inside the A class, which in it's turn executes A z = new A () again, and again, and again...
    and how the same program runs fine by putting a
    static initializer ?Because the static block gets executed only once.
    The use of class- and instance variables is explained in more detail here:
    http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

  • I want to check the main diffrence in Pop up block enabled and disabled.But,i don't get any difference.Would u please help me to understand the difference using one practical example of website

    I want to check the main diffrence in Pop up block enabled and disabled.But,i don't get any difference.Would u please help me to understand the difference using one practical example of website

    Here's two popup test sites.
    http://www.kephyr.com/popupkillertest/test/index.html
    http://www.popuptest.com/

Maybe you are looking for

  • GetDocumentBase returns null in Update 40

    The change to make getCodeBase() and getDocumentBase() return null has broken our FindinSite-CD signed applet which is out in the field on many data CDs and similar, ie running locally.  It doesn't provide any more security as our all-permissions app

  • Preview image does not match content image

    I have been using Bridge CS3 on MAC OS X 10.4 for about 2 years and have happily used it as part of my image processing work flow for thousands of images. A Canon 1DS is my main camera. Some time ago I have started using a Canon G9 in addition to the

  • Skype crashes when i start it - win 7

    My skype crashes 20 seconds after i open it. Firma con problemas: Nombre del evento de problema: BEX Nombre de la aplicación: Skype.exe Versión de la aplicación: 7.2.60.103 Marca de tiempo de la aplicación: 54eefff4 Nombre del módulo con errores: ltc

  • Portal Editor not supporting Arabic text properly

    Hi All, I am using weblogic portal 10.2 and MySQL 5.0. I am creating arabic Content using Portal Editor. But if arabic content contains any english text , then alignment of arabic content is changing. please suggest me , how to upload arabic content

  • Excluding items from back up and Time Capsule not recognising ext HD

    I'm relatively new to the world of Time Machine and Time Capsule. I have a 250Gb iMac, but because my iTunes library was becoming so large I purchased a Iomega 500Gb ext HD and transferred it over to this where it is currently occupying about 350Gb o