tags:

views:

260

answers:

6

Why should a static method in java accept only final or non final variables within its method, but not static?

For example I have the following method:

public static void myfunc(int somethig)
{                                      
  int a=10;                            
  final int b=20;                      
  static int c=30;   //gives Error why?
}
+2  A: 

You can't have static local variable. It doesn't really make sense.

However you can have a static field in your class.


Resources :

Colin Hebert
Why it doesn't make sense? It should make sense, since C++ made it possible. And it was not only for backwards compatibility with C. Otherwise C++ would only allow static local variables in functions, not methods.
fjsj
@fjsj I'm not an expert in C++, what I'm saying is that there is no need for such things which could be hard to understand (as operator overloading etc.). java is like that, some choices have been made by its creators to make it easy as possible to understand.
Colin Hebert
And to tell the truth, it would be (I exagerate obviously) like asking "why there isn't `goto` in java whereas there is `goto` in C and C++"
Colin Hebert
@Colin HEBERT "some choices have been made by its creators to make it easy as possible to understand." - now that is answering the question!
fjsj
@Colin Hebert I personally think that your statement about the ease of understanding is correct only for the 4th edition of the language. That one that didn't have generics and crazy enums in it (annotations were fine however). When Java 5 hit the floor it was a disaster for me - great libraries had to be consumed by a crapy language. It was designed more with C# in mind. The features it introduces have definitely failed to meet the aforementioned goal to be as possible to understand.
nixau
Thanks for suggestion
Android_programmer_office
A: 

Static local variables doesn't exists in Java. You can't use them. Try using static class variables instead.

Vivien Barousse
The question is: why not?
reinierpost
Because it doesnt make sense to use them... the context in which the variable is defined is already static, so why make a already static variable static again? static static is weired :D
WarrenFaith
@reinierpost in C it makes sense because there isn't the whole OOP with classes which can handle static fields. In C++ it makes sense because it must be compatible with C. In java, no needs for that.
Colin Hebert
Why there is no need for that? You guys are not answering the true question. Static variables are nice in C++ when you need to store state between many calls of the same method. Of course there is another way to have the same behavior. The question is, why IN JAVA, you shouldn't (and you can't) do that.
fjsj
@fjsj: You have to read the comments, twice an answer...
WarrenFaith
@WarrenFaith: Putting static modifier in local variables inside a static method doesn't make them "static static". At least not in C++. Since Java is designed to be "familiar (because it looks like C and C++)" you could expect Java static local fields to have similar behavior of C++ static local fields. But Java does not have static local fields. Maybe because it is designed to be "simple (from removing features)". Simple and Familiar source: oracle.com/technetwork/java/simple-142339.html#343
fjsj
Do yourself a favor and don't compare languages just because they "look familiar". Your source is ideal to understand why you shouldn't simply compare... Colin Herbert gave the best reason: `no need for that...` so why implemented unneeded features? -> "simple (from removing features)"
WarrenFaith
I am not comparing Java and C++ because they "look familiar", but because Java was made to look familiar to C++! "No need for that" is not a good answer. "No need for that because Java is designed to be simple" is a good answer. With some effort you don't need Java also...
fjsj
If you need to store a value between method calls in a static method you are not using java in the way it is intended to be used. If you feel you want to do this use a static reference to an object that has the desired function. Java is very strict in the things that it allows. Sometimes this makes life complicated but it also make the code more readable by other java programmers.
Janusz
@Janusz That is true! So it is or not a better answer than "no need for that..."?
fjsj
@fjsj: Simple answer: Java wants you to use a class static or instance variable instead.
R. Bemrose
Thanks for suggestion
Android_programmer_office
+1  A: 

You can not have a static variable. There is no such thing. You can have a class variable as static instead.

Dheeraj Joshi
Thanks for suggestion
Android_programmer_office
+3  A: 

In Java (in Object Oriented Programming in general), objects carry state. Methods should share state through objects attributes, not through static variables.

fjsj
+9  A: 

The question is: why not?

Consider this: what would a static local variable mean?

I suggest that the only sensible meaning would be that this:

public class Foo {
    static int bar = 21;
    public void foo() {
        static int bar = 42;  // static local
        return bar;
    }
}

is equivalent to this:

public class Foo {
    static int bar = 21;
    private static foo$bar = 42;  // equivalent to static local
    public void foo() {
        return bar;
    }
}

In other words, (hypothetical) static locals would be equivalent to regular static attributes with slightly different visibility rules.

The Java language designers probably considered this, and decided that static locals added so little of real value that they were not worth including in the language. (Certainly, that's the way I would have voted.)

Stephen C
that's a decent answer. It is true that such a feature would be rarely used and would have a C++ smell, but still sometimes I really miss that neat trick. There are times when all I need is "a local with slightly different visibility rules". And I don't really understand how can people compare it with a notorious goto operator. Goto is a crap by definition, static locals aren't
nixau
@nixau - the fact that you miss them at all says something about your programming style. Generally speaking, it is good style to avoid using statics, and when you have to use them to use the Singleton design pattern.
Stephen C
@Stephen C: I think you're turning this argument upside down: the fact that Java doesn't offer them at all necessitates the Singleton pattern, which I rarely need in other languages. Most patterns are workarounds for lacking features in the Java language. If the language supported them instead, they would be much easier to recognize by developers and by compile-time tools so it would be easier to apply them correctly.
reinierpost
@reinierpost - no I am not. The reason that statics are frowned upon is nothing to do to with not having static locals. It is because statics lead to problems making applications reentrant, problems exploiting parallelism, problems with reusing code and so on.
Stephen C
@Stephen C common dude, you're exaggerating. it's a simple static local variable which is not visible outside the method scope. If the dev is stupid enough to call such a method from muliple threads without applying any synchronization primitives of the language than you may expect far more serious flaws in the code he produces. The designers of Java language have made this decision and I'm OK with that. However, I've come across several situations where my code would definitely benefit from using the static locals feature.
nixau
In Java I have to explicitly declare a trowaway static variable to achieve my goal. I believe it's the compiler's job to deal with such variables, not mine.
nixau
@nixau - obviously, you've never had to re-engineer code that abuses static variables. It is not a trivial matter.
Stephen C
@Stephen C. I see your point. Re-engineering is a pain. However, I would choose a productivity path if I were a designer of Java language. C# language designers have proven that syntatic sugar is of no harm in case you know what exactly stands behind it (and you can always replace it with your explicit implementation). And re-engineering all those unspeakably named generated variables/classes is a pain and always will be.
nixau
@Stephen C: do you mean that if those developers had used singletons insted of static variables, the code would have been easier to reengineer? Why?
reinierpost
@reinierpost - not exactly. What I mean is that the code would have been easier to reengineer if that hadn't used either. Remember, this thread started with me commenting that @nixau probably used statics too much. See also @fjsj's answer.
Stephen C
@Stephen C: OK, then I understand your argument, but it isn't really an argument against static variables.
reinierpost
@reinerpost - the problem is that the argument against (over-)using statics is complicated and nuanced, and not possible to make effectively in comment thread. Besides, it is off topic for this question.
Stephen C
A: 

Since every function in java has to be inside a class, you can get the same effect by declaring fields in your class. It's the simplest way, and java language designers are very conservative. They'd never add a feature like that, when there's a more obvious and less complex way to do the same thing.

EDIT: I guess philosophically functions aren't first class in java. They're not supposed to store data. Classes are, and they do.

Gary
It is *not* the same effect: now all methods in the class have access to the variable.
reinierpost
ok, but I think in practice, it's totally useless to be able to do that, since if you have access to the source code to one function, you'll be able to see the code of the others. There are no benefits of encapsulation to be gained by limiting the access from functions within the same class. There's no 'information hiding' if you can see it. If that deserves a '-1', I'll take it with pride :-).
Gary
Thanks for suggestion
Android_programmer_office