Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Why can I have static int a, but not int a?

  1. #1
    Junior Member
    Join Date
    Jul 2019
    Posts
    22
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Why can I have static int a, but not int a?

    Why does this work:

    public class demo {
    	static int a;
    	public static void main(String args[]) {		
    		System.out.println(a);				
    	}
     
    }

    But this does not:

    public class demo {
    	int a;
    	public static void main(String args[]) {		
    		System.out.println(a);				
    	}
     
    }

    And this one also does not:
    public class demo {
     
    	public static void main(String args[]) {
    	static int a;		
    		System.out.println(a);				
    	}
     
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Why can I have static int a, but not int a?

    Please copy the full text of the compiler's error message and paste it here.
    The error message should explain what the problem is.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Oct 2019
    Posts
    4
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Why can I have static int a, but not int a?

    In the second case, the "a" variable is not static. Just a package-private instance variable. Instance variables cannot be accessed from a static scope.
    In the third case, you cannot use static keyword inside a method.
    Please note, static variables and methods are related to the class and not the instance.

  4. The Following User Says Thank You to kjaron For This Useful Post:

    jenniferruurs (October 7th, 2019)

Similar Threads

  1. [SOLVED] Game Combat: Fighting one enemy at a time? (Issue with static/non-static?)
    By Rexoa in forum Java Theory & Questions
    Replies: 6
    Last Post: March 2nd, 2014, 07:34 AM
  2. Replies: 6
    Last Post: May 3rd, 2013, 04:25 PM
  3. Replies: 4
    Last Post: November 15th, 2012, 12:09 AM
  4. Replies: 10
    Last Post: September 6th, 2010, 04:48 PM