Results 1 to 3 of 3
  1. #1
    madhuri is offline Member
    Join Date
    Feb 2014
    Posts
    2
    Rep Power
    0

    Default initialization of variables at class level

    if I declare
    class Example
    {
    int x=10;
    ......
    }
    it is not showing any error
    but when I declare
    class Example
    {
    int x;
    x=10;
    ............
    }
    it showing compile time error
    Can anyone give me the reason

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,775
    Blog Entries
    7
    Rep Power
    21

    Default Re: initialization of variables at class level

    Outside a method or an initialization block no statements are allowed (e.g. you can't do 'for (int i= 0; i < 10; i++) ...' there either); the first example is simply a variable definition with an initialization while the second example is a variable definition (which is ok) and an assignment expression (which is a statement and not ok here).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    madhuri is offline Member
    Join Date
    Feb 2014
    Posts
    2
    Rep Power
    0

Similar Threads

  1. Replies: 11
    Last Post: 11-04-2012, 10:26 PM
  2. instance variables initialization
    By ghostrider in forum New To Java
    Replies: 6
    Last Post: 08-27-2012, 08:00 AM
  3. Class Instance initialization fails
    By JOHNINALBANY in forum New To Java
    Replies: 3
    Last Post: 07-08-2012, 08:43 PM
  4. An Array of Objects (Class Initialization)
    By Chris_C in forum New To Java
    Replies: 9
    Last Post: 02-09-2011, 06:49 AM
  5. [SOLVED] Class-level vs Object-level method()
    By mfaizan24 in forum New To Java
    Replies: 7
    Last Post: 06-23-2009, 10:18 AM

Tags for this Thread

Posting Permissions

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