Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variables in Static method

 
J Brewer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just tried the exumalator's question of the day, and I have a question:




1. char h = 1; //on the line before the System.out.println statement.
2. static char h = 1; //On the line before the System.out.println statement
3. char h = 1;//On the line before the main method
4. static char h = 1;//On the line before the main method


The answer is listed as 1 and 4, which is fine, but I also think 2 is also an option. Can't you put static variables inside a static method?
 
Peter MacMillan
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by J Brewer:
Can't you put static variables inside a static method?


No. Only the final modifier is allowed.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, static is a modifier you use on class variables and methods.
 
J Brewer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, that's what I thought at first. But then I saw one source that said 'you can have static variables inside a static method', so I wasn't sure.

Thanks!
 
Sujittt Tripathyrr
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Here I have one doubt that in general method we can put static variable but in static method why not.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is only one modifier can be used by local variables that is final modifier.
 
Suhas Wadadekar
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i agree with Owen.....we cannot have any other variable modifier inside a method. As listed in the rules governing staic declarations in K & B book, I think that anything that is method-local cannot be static.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic