Discussions

EJB programming & troubleshooting: Class Initialization

  1. Class Initialization (4 messages)

    Hi,
    For the following class :
    class tryme
    {
      static int i = 5;
      static{
       int i = 7;
      }
    // static int i = 5;
    public static void main(String[] args)
    {
           System.out.println(i);
    }
    }
    The output is 5 irrespective of position of static block relative to declaration of i.
    But in the following code,the output depends on the position of the static block.(Gives 5 in this case and gives 7 when the upper static block is commented and lower one uncommented.)

    class tryme
    {
       static{
          setI();
       }
       static int i = 5;
        /*static
        {
            setI();
        }*/

        private static void setI()
        {
    i = 7;
        }
        public static void main(String[] args)
        {
               System.out.println(i);
        }
    }

    What is the reason for this?

    Thanks n Regards

    Threaded Messages (4)

  2. Class Initialization[ Go to top ]


    Hi,

    Couple of points:

    1. If you are being employed as a programmer, tell your boss to fire you.

    2. This forum is about EJB... not random java questions about bad coding style.

    3. Buy a Java book and look up "scope" in the index.

    Cheers,

    Daniel.
  3. Class Initialization[ Go to top ]

    Heh, somebody woke up on the wrong side of the bed this morning...

    In the first case, the "i" declared within the static block is not the same as the static "i" class member. If instead of "int i = 7" you had written "i = 7" the code would refer to the static i, and you would get the results you expect.
    Basically when you define a variable in a scope, that has allready been defined in the outer scope, two different variables are defined. The code inside the inner scope would access the inner variable; the rest of the code will access the outer one.

    The Java Tutorial on java.sun.com probably explains these issues in fair detail.

    Gal
  4. Class Initialization[ Go to top ]

    Yeah, that's what I said isn't it :-)

    I just get the feeling that, that sort of stuff is covered in the first chapter of "Programming for Dummies".

    Besides, I slept on the couch...

    Daniel.
  5. Class Initialization[ Go to top ]

    Slept on the coach? Ahh, that explains it... :)

    It probably is. That's why I recommended the Java Tutorial.

    Gal