File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes simple question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "simple question" Watch "simple question" New topic
Author

simple question

Mario Gimenez
Ranch Hand

Joined: Mar 23, 2010
Posts: 38
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

Joined: Oct 13, 2009
Posts: 774

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,

Prithvi,
My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
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

Joined: Mar 23, 2010
Posts: 38
Thank you very much for your help.

Prithvi Sehgal
Ireneusz Kordal
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
You are welcome mate.

Happy preparation.

Best Regards,
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
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 ... ...


BEE MBA PMP SCJP-6
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14338
    
  22

Please UseAMeaningfulSubjectLine when you post a question (instead of something like "simple question").


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: simple question