permaculture playing cards
The moose likes Java in General and the fly likes static variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "static variables" Watch "static variables" New topic

static variables

Divya Venkatesh

Joined: Nov 05, 2002
Posts: 28
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
illegal start of expression
static int seqnumber=1;
./ cannot resolve symbol
symbol : variable seqnumber
location: class CliSender
String result=data+"="+seqnumber;
please let meknow if it is illegal


Joined: Feb 26, 2001
Posts: 10
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

Joined: Jul 11, 2001
Posts: 14112
Why do you want to declare a static variable inside a method?

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
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?

"JavaRanch, where the deer and the Certified play" - David O'Meara
Wilfried LAURENT
Ranch Hand

Joined: Jul 13, 2001
Posts: 269
It looks like C programming, where you sometimes want to keep a counter inside a method, doesn't it ?
I agree. Here's the link:
subject: static variables
It's not a secret anymore!