Hi group
Is there some way to emulate in Java the semantics of the C-style
function-level static variable that preserves its value across function
calls ?
void show()
{
static int i = 0;
printf("Value is %d",i); // Prints 1.2.3... on multiple calls
to show()
i++;
}
I can perhaps use an instance variable, but it would be visible from
all other methods as well (and also creates a dependency on a variable
outside the method). I tried "static" itself in Java, but the compiler
complains loudly....
sb
Chris Smith - 24 Jul 2005 15:24 GMT
> I can perhaps use an instance variable, but it would be visible from
> all other methods as well (and also creates a dependency on a variable
> outside the method). I tried "static" itself in Java, but the compiler
> complains loudly....
A field is the way to go. Classes are the unit of encapsulation in
Java. If you only want to use the variable from one method, then just
don't use it anywhere else. If the class is big enough that you can't
easily manage this, then refactor into smaller classes.

Signature
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
Indudhar - 24 Jul 2005 15:53 GMT
Would this work?
class MyCounter{
private static int i = 0;
public static void showValue(){
System.out.println( i++);
}
}
//call to the method
MyCounter.showValue();
just curious...
Tor Iver Wilhelmsen - 24 Jul 2005 15:42 GMT
> Is there some way to emulate in Java the semantics of the C-style
> function-level static variable that preserves its value across function
> calls ?
Yes: Put the function in a final class by itself, and use a private
variable for what you want.
Alan Krueger - 24 Jul 2005 16:04 GMT
> Hi group
> Is there some way to emulate in Java the semantics of the C-style
[quoted text clipped - 8 lines]
> i++;
> }
In C, a static local variable is initialized the first time the function
containing it is called. I'm not sure what the multithreading semantics
of this feature are, though.
What you'll want is a static field. This will be initialized when the
class is loaded. Here's some test sample code missing any synchronization:
public class Foo {
public static void show() {
System.out.println( "Value is " + value++ );
}
public static void main( String[] args ) {
for ( int i = 0; i < 4; ++i )
show();
}
private static int value = 0;
}
> I can perhaps use an instance variable, but it would be visible from
> all other methods as well (and also creates a dependency on a variable
> outside the method). I tried "static" itself in Java, but the compiler
> complains loudly....
Since you're in control of the class (make it a final class if you're
worried), you're in control of what accesses that field. Don't use a
non-static (instance) field, there will be a separate one for each
instance of the class. (Unless your C code looks like it's modelling a
class with instances, but the sample you attached didn't.)