Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

simple question

 
Mario Gimenez
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. First of all. I'm sorry but I couln't find this in the FAQs.
My question its simple. Why a can't declare a static variable into main ???


But if I put final its works...
I couldn't understad.


Thanks a lot.
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Local variables can't have any modifiers except final. It is not for main only if you try something like
this


The above mentioned code won't compile, because static can't be applied to local variables. Additionally static variables
are class variables and not related to any instance. In your example, it was a local variable and static is not allowed with it.

Hope this helps,
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mario Gimenez wrote:
My question its simple. Why a can't declare a static variable into main ???

Answer is also simple - because java specification doesn't allow to declare local variables as static - see here:
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.4
static modifier is only allowed for class members (fields). Variable inside a method is formally called 'local variable'.
 
Mario Gimenez
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your help.

Prithvi Sehgal
Ireneusz Kordal
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome mate.

Happy preparation.

Best Regards,
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Local method variables cannot be static, which would make them stick around without a class
instance, because they disappear from the stack when the method returns. Also by default,
they are private to the method and cannot be accessed from above or below; from calling or
called methods. So access modifiers public, protected and private don't make sense for local
variables either (or parameter passing variables).

Jim ... ...
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseAMeaningfulSubjectLine when you post a question (instead of something like "simple question").
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic