Results 1 to 2 of 2
  1. #1
    phobosforever is offline Member
    Join Date
    Jul 2011
    Posts
    1
    Rep Power
    0

    Default Static Block and variable problem

    Here is a code that I encountered while working on the Eclipse IDE.

    class Demo
    {
    static
    {
    x = 100;
    System.out.println(x);
    }

    public static void main(String args[])
    {
    //System.out.println(x);
    }

    static int x =1000;
    }

    Inside the static block, at the prin statement, it gives me an error "Cannot reference a field before it is defined", whereas, if I comment that, and uncomment the print statement inside main, it works fine. What seems to be the problem here?

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,242
    Rep Power
    19

    Default

    Classes
    The static initializers and class variable initializers are executed in textual order.

    Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope. See 8.3.2.3 for the precise rules governing forward reference to class variables.
    db

Similar Threads

  1. Replies: 5
    Last Post: 12-01-2010, 06:43 AM
  2. Replies: 5
    Last Post: 10-15-2010, 04:21 AM
  3. Replies: 3
    Last Post: 02-11-2010, 09:59 AM
  4. [SOLVED] static block or constructor?
    By JT4NK3D in forum New To Java
    Replies: 3
    Last Post: 05-27-2008, 02:21 PM
  5. Replies: 1
    Last Post: 08-01-2007, 09:25 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •