File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

static variables

Divya Venkatesh
Greenhorn

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
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


Divya
rudhras
Greenhorn

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
author
Sheriff

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"
Sheriff

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 ?
W.
 
 
subject: static variables
 
Similar Threads
for Loops with PrintWriter
question regarding initialzer.
Help Please
HeadFirst DotComBust... Help?
Problem with protected variable...