Results 1 to 6 of 6
  1. #1
    rqal.10 is offline Member
    Join Date
    May 2008
    Posts
    1
    Rep Power
    0

    Question variable initialization

    Following code giving error:
    class A{
    int a;
    a=1;
    }
    but following code working fine:
    class A{
    int a=1;
    }

  2. #2
    theonly is offline Member
    Join Date
    Apr 2008
    Posts
    23
    Rep Power
    0

    Default

    What error is java giving you?

  3. #3
    danielstoner's Avatar
    danielstoner is offline Senior Member
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    191
    Rep Power
    6

    Default

    Come on :) You cannot do a=1; in the class body. You have to put that in a method, static bloc or initialize the variable on the same line where you declare it like in second example.
    Daniel @ [www.littletutorials.com]
    Language is froth on the surface of thought

  4. #4
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    Yes, according to the code segment you have to use non-static initialization block as follows.

    Java Code:
    class A {
       int a;
    
       {
            a = 1;
       }
    }

  5. #5
    ferranb is offline Member
    Join Date
    Jun 2008
    Posts
    22
    Rep Power
    0

    Default

    In the first example, "a=1" is an assigment sentence, and assigment sentences only are allowed inside methods.

    The second one is an initializer declaration and can be on classes attributes or local variables.

    Ferran

  6. #6
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    Quote Originally Posted by ferranb View Post
    In the first example, "a=1" is an assigment sentence, and assigment sentences only are allowed inside methods.
    Inside installation blocks too. Normally we don't call them as methods. :)

Similar Threads

  1. Initialization and re-assignment of arrays
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-14-2008, 08:38 PM
  2. initialization value problem
    By ravian in forum New To Java
    Replies: 2
    Last Post: 01-28-2008, 10:54 AM
  3. Icon initialization problem
    By saz25 in forum AWT / Swing
    Replies: 1
    Last Post: 12-24-2007, 10:37 PM
  4. Lazy Initialization
    By onegcr in forum New To Java
    Replies: 1
    Last Post: 08-14-2007, 03:29 PM
  5. log4j initialization
    By arfatkhan in forum Web Frameworks
    Replies: 3
    Last Post: 08-10-2007, 07:42 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
  •