• Post Reply Bookmark Topic Watch Topic
  • New Topic

Local Static variables ?  RSS feed

 
Nikhil Sagar
Ranch Hand
Posts: 216
Java Linux Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think we can't have a local static variable, if i am correct then why ?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If it was allowed, what do you think it would mean? The main reason it's not allowed is that it doesn't make sense.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew: In C and C++, you can have local static variables. The scope of such variables is the method they are defined in, but they continue to exist when the method ends. Next time the same method is called, such a variable will still have the value it had when the method was called the previous time.

Although Java took a number of features from C++, it isn't the same as C++, and this feature was left out. Probably the designers of the Java language didn't think this was a very useful feature to borrow from C++. If that was their reason then I'd agree with them - this is not a feature that you really need, and it can be hard to understand.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True, I'd forgotten about that (and even when I used to use C++, I don't think I ever used the feature). Thanks. Thinking about it, I think there are other uses of "static" in C that don't quite correspond to the meaning in Java (e.g. C "static functions" are not the same as Java "static methods").
 
Nikhil Sagar
Ranch Hand
Posts: 216
Java Linux Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now i got it,
thanks Jesper
Thanks Matthew
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have seen that similarity between Java™ and C++ cause confusion before. There are several places where the two languages have similar syntax, but different semantics, and many people get confused by them.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!