We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,756 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Help: Adding static variable confusion. Inside or outside main()?

Hey guys,

I'm a starter so I had a doubt related to placement of a static variable. On line 5, for "static int d=5" compiler issues "illegal start of expression". But when I place it outside main() as Instance variable it works and prints "Hello 5". Why this thing?

  public class AbstractClass {      

  public static void main(String args[]) {      
      String s = "Hello";       
      static int d=5;       
      System.out.println(s);        
      System.out.println(d);
      } 
  }
3
Contributors
4
Replies
2 Days
Discussion Span
10 Months Ago
Last Updated
5
Views
Question
Answered
rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

hi rahul.ch ,
We cant declare static varibale as local method variable
because static variables are belongs to class not object ,we can acess the staic variable using class name directly, When you declare a variable inside method(staic or non static) it is local varible we could not access out side the class.

anand01
Posting Whiz in Training
288 posts since Aug 2010
Reputation Points: 12
Solved Threads: 22
Skill Endorsements: 0

Thanks a lot anand. Appreciate the clarity.

rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

actually, we can't declare a local variable as being static :) (potato, potatoe)
you have three options: either you have it as a local (non-static) variable that is defined within the main method, or you have it on class scope, either static or non-static.

stultuske
Industrious Poster
4,370 posts since Jan 2007
Reputation Points: 1,318
Solved Threads: 610
Skill Endorsements: 23

Thanks stultuske :)

rahul.ch
Junior Poster in Training
90 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 10 Months Ago by stultuske and anand01

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0670 seconds using 2.67MB