Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2007

Tip: Looking for answers? Try searching our database.

Why can't i declare a static variable in a static method?

Thread view: 
ZelluX - 15 Nov 2007 10:12 GMT
for example,
class Test {
   public static void main(String[] args) {
       double radius = 5;
       static double PI = 3.15169;
       double area = radius * radius * PI;
       System.out.println("Area is " + area);
   }
}

I can't figure out why it is wrong
thanks
visionset@yahoo.com - 15 Nov 2007 10:17 GMT
>  Why can't i declare a static variable in a static method?

A local variable exists (or rather before eligible for GC) only for
the scope of the method, so the concept of static is not relevant.

--
mike w
Chris Dollin - 15 Nov 2007 10:30 GMT
>>  Why can't i declare a static variable in a static method?
>
> A local variable exists (or rather before eligible for GC) only for
> the scope of the method, so the concept of static is not relevant.

There's nothing wrong with the idea of a static local variable, which
would be a static variable whose scope was restricted to the block
(hence method) in which it is declared. (Naturally an initialiser
for such a variable would not be allowed to refer to non-static locals.)

It's just that Java doesn't have them: I have no idea why.

Signature

Chris "perhaps method calls generate friction => sparks?" Dollin

Hewlett-Packard Limited registered office:                Cain Road, Bracknell,
registered no: 690597 England                                    Berks RG12 1HN

Christian - 15 Nov 2007 10:20 GMT
ZelluX schrieb:
> for example,
> class Test {
[quoted text clipped - 8 lines]
> I can't figure out why it is wrong
> thanks

java does not have this concept of a variable that doesn't change during
calls..

what you can do is declare the variable outside the method static..
(static final is java's version of a constant)

like
class Test {

    private static final double PI = Math.PI ;

    public static void main(String[] args) {
        double radius = 5;
        double area = radius * radius * PI;
        System.out.println("Area is " + area);
    }
}
Chris Dollin - 15 Nov 2007 10:33 GMT
> ZelluX schrieb:
>> for example,
[quoted text clipped - 12 lines]
> java does not have this concept of a variable that doesn't change during
> calls..

You can declare locals `final` -- doesn't that count?

Signature

Chris "then ZZ1, ZZ2 ZZ3" Dollin

Hewlett-Packard Limited registered office:                Cain Road, Bracknell,
registered no: 690597 England                                    Berks RG12 1HN

Christian - 15 Nov 2007 11:54 GMT
Chris Dollin schrieb:

>> ZelluX schrieb:
>>> for example,
[quoted text clipped - 13 lines]
>
> You can declare locals `final` -- doesn't that count?

nope ... doesn`t count ... the next call to the method the local will
have the value to which it is initialized to in the current call..
not the value to which it was initialized to with the first call.

Signature

java only has global variables for this.. there are no global variable
with scope to one method..

Chris Dollin - 15 Nov 2007 12:06 GMT
> Chris Dollin schrieb:
>>
[quoted text clipped - 15 lines]
>>
>> You can declare locals `final` -- doesn't that count?

> nope ... doesn`t count ... the next call to the method the local will
> have the value to which it is initialized to in the current call..
> not the value to which it was initialized to with the first call.

Indeed, but it fits your "variable that doesn't change during calls"
description, I thought.

I don't see that it's anything to do with /changes/ to the variable.
Java just doesn't allow statics that are scoped within a method.
It has a notion of variables that don't change during calls -- final
variables (local or not), and a notion of variables that do change
(non-final, local or not.)

Signature

Chris "disentangling" Dollin

Hewlett-Packard Limited registered office:                Cain Road, Bracknell,
registered no: 690597 England                                    Berks RG12 1HN

Lew - 15 Nov 2007 12:38 GMT
Chris Dollin schrieb:
>>> You can declare locals `final` -- doesn't that count?

Christian wrote:
>> nope ... doesn`t count ... the next call to the method the local will
>> have the value to which it is initialized to in the current call..
>> not the value to which it was initialized to with the first call.

> Indeed, but it fits your "variable that doesn't change during calls"
> description, I thought.

Except that it does change between calls.

> I don't see that it's anything to do with /changes/ to the variable.
> Java just doesn't allow statics that are scoped within a method.
> It has a notion of variables that don't change during calls -- final
> variables (local or not),

Except that a final local variable does change between calls.

> and a notion of variables that do change (non-final, local or not.)

Except that it's a different final local variable with each call.

Signature

Lew

Chris Dollin - 15 Nov 2007 13:45 GMT
> Chris Dollin schrieb:
>>>> You can declare locals `final` -- doesn't that count?
[quoted text clipped - 8 lines]
>
> Except that it does change between calls.

I don't think so ...

> Except that it's a different final local variable with each call.

... and that's why; each call has it's own locals; but those locals
don't exist once the call terminates.

Signature

Chris "can non-existant things change?" Dollin

Hewlett-Packard Limited registered office:                Cain Road, Bracknell,
registered no: 690597 England                                    Berks RG12 1HN

Lew - 15 Nov 2007 13:50 GMT
>> Chris Dollin schrieb:
>>>>> You can declare locals `final` -- doesn't that count?
[quoted text clipped - 12 lines]
> .... and that's why; each call has it's own locals; but those locals
> don't exist once the call terminates.

And you don't regard a brand-new instance as a change?

Signature

Lew

Chris Dollin - 15 Nov 2007 14:30 GMT
(fx:snipping)

>> .... and that's why; each call has it's own locals; but those locals
>> don't exist once the call terminates.
>
> And you don't regard a brand-new instance as a change?

It's /a/ change, but it's not a change to "the" variable.

Signature

Chris "existence is not a predicate, or something like that" Dollin

Hewlett-Packard Limited     Cain Road, Bracknell,                registered no:
registered office:          Berks RG12 1HN                       690597 England

Christian - 15 Nov 2007 14:44 GMT
Chris Dollin schrieb:

> (fx:snipping)
>
[quoted text clipped - 3 lines]
>
> It's /a/ change, but it's not a change to "the" variable.

huh?

void foo() {
  static Bar bar = new Bar(getCurrentTime());

  bar.printTime();  //will print allways the same
}

java

void foo() {
  final Bar bar = new Bar(getCurrentTime());

  bar.printTime();  //will print allways the currentTime
}

so yes the variable is still called bar...
but what does not change beside this?
Chris Dollin - 15 Nov 2007 15:04 GMT
> Chris Dollin schrieb:
>>
[quoted text clipped - 14 lines]
> so yes the variable is still called bar...
> but what does not change beside this?

Any given variable `bar` of `foo` has a single value that does not change.

It doesn't matter that there are arbitrarily many different variables all
called `bar` with different values at different times.

[Saying "/the/ variable", as above, is misleading, IMAO.]

Signature

Chris "singular and mutable" Dollin

Hewlett-Packard Limited registered office:                Cain Road, Bracknell,
registered no: 690597 England                                    Berks RG12 1HN

Knute Johnson - 15 Nov 2007 18:01 GMT
>> Chris Dollin schrieb:
>>>
[quoted text clipped - 19 lines]
>
> [Saying "/the/ variable", as above, is misleading, IMAO.]

I hear static locals are coming.  I'm not sure if they will be in 1.7 or
not but they have been discussed at some length here recently.  There is
a name for them too, anybody remember what it is?  CRS you know :-).

Signature

Knute Johnson
email s/nospam/knute/

Roedy Green - 15 Nov 2007 23:08 GMT
>for example,
>class Test {
[quoted text clipped - 8 lines]
>I can't figure out why it is wrong
>thanks

I have asked Sun to make that legal.  It would give you a static
variable accessible only by one method. It would not even need a
change to the JVM, just the compiler. Perhaps you could submit an RFC.

See http://mindprod.com/jgloss/rfc.html

For now you must define a private static variable accessible to all
methods in the class.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Jim Korman - 16 Nov 2007 03:45 GMT
>>for example,
>>class Test {
[quoted text clipped - 17 lines]
>For now you must define a private static variable accessible to all
>methods in the class.

I'm not sure I'm seeing how a method scoped static would be used.

Is the idea that the value would maintain its value between calls to
the method, but keep the scope local to the method?  If so how
would you keep the declaration from overwriting the previously set
value?

Jim
Roedy Green - 16 Nov 2007 05:12 GMT
>I'm not sure I'm seeing how a method scoped static would be used.
>
>Is the idea that the value would maintain its value between calls to
>the method, but keep the scope local to the method?  If so how
>would you keep the declaration from overwriting the previously set
>value?

It would behave exactly like a private static.  It would be
initialised to 0/null. However, it would be declared in a method, and
any references to it outside that method would be illegal, detected an
compile time.

You would use it for example in

void myMethod ()
{
static Random wheel;
// first use init.
if( wheel == null ) wheel = new Random();

for (int i=0;i<100;i++)
 {
System.out.println( wheel.nextInt( 6 ) );
}
}

You are declaring that wheel is purely for the use of myMethod, but
other than that in is like a private static.

To allow one-time initialisation would get fairly hairy. That is why I
side-stepped the issue.  Perhaps inability to init is a reasonably
easily defined way is why Sun did not allow this. It would be a wart
no matter how it was handled.

Another syntax would be something like this where you declare outside
the method.

private to myMethod static Random wheel = new Random();

you could also have private instance methods too:

private to myMethod Random wheel = new Random();
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Jim Korman - 17 Nov 2007 02:04 GMT
>>I'm not sure I'm seeing how a method scoped static would be used.
>>
[quoted text clipped - 38 lines]
>
>private to myMethod Random wheel = new Random();

Thanks for the discussion. The first time initialization was one of
the issues that had me questioning. Food for thought.

Jim
Mark Space - 18 Nov 2007 03:47 GMT
o allow one-time initialisation would get fairly hairy. That is why I

One could just write

class C {
    static void m() {
        static int i = 10;
        // ... etc. use i here
    }
}

And have it understood that the assignment is only executed once, on
class load.  It's a little hard to read, but not that much.
Patricia Shanahan - 18 Nov 2007 04:16 GMT
> o allow one-time initialisation would get fairly hairy. That is why I
>
[quoted text clipped - 9 lines]
> And have it understood that the assignment is only executed once, on
> class load.  It's a little hard to read, but not that much.

Maybe it would be better with a different syntax:

class C {
  private {
    static int i = 10;
    void m() {
        // ... etc. use i here
    }
  }
  void n() {
     // No access to i here.
  }
}

That is, group a method and its method-local fields in a "private
block". I think this additional keyword use should be unambiguous - the
other uses of "private" are followed by a keyword or an identifier.

The variable would be declared static or not depending on whether it
should have a single value for all instances or not. The braces show the
scope limitation. The placement outside the method shows that it is a
field, not a local variable.

If the field is static, its initializer is executed on class load. If it
is non-static, its initializer is executed during object creation.

More generally, it is a normal private field declaration, with the
single exception that it can only be referenced in one method.

Patricia
Lasse Reichstein Nielsen - 18 Nov 2007 12:10 GMT
> More generally, it is a normal private field declaration, with the
> single exception that it can only be referenced in one method.

This scope construction also has the advantage that it scales to
fields only referencable by *more* than one method, but not all.

private {  
  static int i = 0;
  public int next() {
     return i+1;
  }
  public void reset() {
     i = 0;
  }
}

Then again, is it really necessary to hide fields from their *own* class?

/L
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'

Patricia Shanahan - 18 Nov 2007 14:48 GMT
>> More generally, it is a normal private field declaration, with the
>> single exception that it can only be referenced in one method.
[quoted text clipped - 6 lines]
>    public int next() {
>       return i+1;

"return i++;" would be more interesting.

>    }
>    public void reset() {
[quoted text clipped - 3 lines]
>
> Then again, is it really necessary to hide fields from their *own* class?

That I am very unsure about. My general feeling is that it is possible
the class is too large, and a candidate for refactoring, if this is
really an issue.

For example, maybe those methods in your example should be replaced by a
nested class called something like "Counter".

Patricia
Lew - 18 Nov 2007 16:31 GMT
>>> More generally, it is a normal private field declaration, with the
>>> single exception that it can only be referenced in one method.
[quoted text clipped - 22 lines]
> For example, maybe those methods in your example should be replaced by a
> nested class called something like "Counter".

The point is that no language will or can have every possible feature every
possible programmer could possibly ever want.  What it can have, as Java does,
is a way to get every possible task done.  If the idiom you crave doesn't
exist, switch languages or use the equivalent feature that does exist.

Signature

Lew

Hendrik Maryns - 19 Nov 2007 11:58 GMT
Roedy Green schreef:

>> I'm not sure I'm seeing how a method scoped static would be used.
>>
[quoted text clipped - 38 lines]
>
> private to myMethod Random wheel = new Random();

Eiffel has ‘once’ methods, which seem to do exactly what you do here.
Might be something worth looking at, or referencing in the bug you made
at Sun’s.

H.
Signature

Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Stefan Ram - 18 Nov 2007 04:45 GMT
>public static void main(String[] args) {
>  double radius = 5;
>  static double PI = 3.15169;
>  double area = radius * radius * PI;
>  System.out.println("Area is " + area);

public class Main
{ public static void main( final java.lang.String[] args )
 { double radius = 5;
   class Const { final static double PI = 3.15169; };
   double area = radius * radius * Const.PI;
   java.lang.System.out.println( "Area is " + area ); }}

Area is 78.79225

 NB: Without the second »final« this instead yields:

Main.java:4: inner classes cannot have static declarations
   class Const { static double PI = 3.15169; };
                               ^


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.