java question about static variable in static method

A

Aakash

HI, I have a simple program which does not compile:
public class class1{

public static void main(String[] args)
{
static int i=0;//static is not allowed, why?
}

}

Can you tell me why this is not allowed?
Thanks
Aakash
 
K

Knute Johnson

Aakash said:
HI, I have a simple program which does not compile:
public class class1{

public static void main(String[] args)
{
static int i=0;//static is not allowed, why?
}

}

Can you tell me why this is not allowed?
Thanks
Aakash

Static variables may only be class variables. There is some discussion
about 'closures', which are supposed to be like static variable, being
added in version 7.
 
L

Lasse Reichstein Nielsen

Aakash said:
HI, I have a simple program which does not compile: ....
public static void main(String[] args)
{
static int i=0;//static is not allowed, why?
} ....
Can you tell me why this is not allowed?

Because it is not part of the Java syntax.

More relevantly: What would you expect it to do?

If you want something like static local variables in the C language,
it does not exist in Java. Instead use a private field on the object
that the method belongs to, that restricts access to methods in the
class instead of just the one method, but it should solve the same
problems that the C static local variable does.

/L
 
R

Roedy Green

public static void main(String[] args)
{
static int i=0;//static is not allowed, why?
}

}

Can you tell me why this is not allowed?

This is Java, not C++. You must declare statics outside methods. They
belong to the class, not to a particular method. I think the reason
it was not is initialisation. Does it get inited every method
execution, just the first time? In what context? It was too messy to
define that, so they disallowed it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top