Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variables

 
Divya Venkatesh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi i want to know i can decalre a variable static within a function.Look at this code
String createPacketData()
{
static int seqnumber=1;
String data="Content Number";
String result=data+"="+seqnumber;
return (result);
}
Iam geting many errors when i try to declare a varible static within the Function
HERE IT IS:
illegal start of expression
static int seqnumber=1;
^
./CliSender.java:31: cannot resolve symbol
symbol : variable seqnumber
location: class CliSender
String result=data+"="+seqnumber;
please let meknow if it is illegal
thanks
 
rudhras
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot declare a variable in any functional blocks as the static variables are class variables.Declare outside the any methods and use them as required.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you want to declare a static variable inside a method?
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All variables declared inside methods are local to the method. That means that the value of the variable is stored in the stack instead of in an object on the heap (like a member variable) or in memory related to the classfile (like a static variable).
When the method ends - the stack is disposed of, and the value of the variable is gone - poof!
A static variable must stick around forever to be available to any object that whats to use it.
If it must be static try it this way:

But I expect that it really does not need to be static. What are you trying to accomplish?
 
Wilfried LAURENT
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks like C programming, where you sometimes want to keep a counter inside a method, doesn't it ?
W.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic