Is there a way to use internal static variables in Java? eg take this C code:
void increment(){
static int i = 0;
i++;
printf("%i",i);
}
How would I do this in Java?
Java doesn't have any direct equivalent - all state which you want to be persisted across method calls has to be stored in fields rather than local variables. So you can have this:
private int counter = 0;
public void increment() {
counter++;
System.out.println(counter);
}
... but of course the other methods in the same class have access to counter
as well.
for the same purpose you will have to re-write the code as per the java standard. declare the variable outside the method. It need not be static if you just want to access inside the method.
int i = 0;
void increment(){
i++;
System.out.println(i);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.