Related Topics
Static in C and JAVA
The keyword “static” has different meanings and uses in C and Java.
In C, the keyword “static” is used to modify the scope and lifetime of variables and functions within a program. When used with a variable declared within a function, it indicates that the variable should retain its value between function calls, and its scope is limited to the function in which it is declared. When used with a function, it indicates that the function should be visible only within the file in which it is defined.
In Java, the keyword “static” is also used to modify the scope and lifetime of variables and functions, but in a different way. When used with a variable or method, it indicates that it belongs to the class itself rather than to any instance of the class, and can be accessed without creating an instance of the class. This means that the variable or method can be shared among all instances of the class. Additionally, static methods cannot access non-static members of a class, as they do not have access to instance-specific data.
Here are some examples of the use of “static” in C and Java:
/* C Coding */
#include <stdio.h>
void increment_counter() {
static int counter = 0; // static variable retains its value between function calls
counter++;
printf("Counter value: %d\n", counter);
}
int main() {
increment_counter();
increment_counter();
increment_counter();
return 0;
}
/* Output */
Counter value: 1
Counter value: 2
Counter value: 3
/* JAVA Coding */
public class Example {
static int counter = 0; // static variable belongs to the class itself
static void incrementCounter() {
counter++;
System.out.println("Counter value: " + counter);
}
public static void main(String[] args) {
incrementCounter();
incrementCounter();
incrementCounter();
}
}
/* Output */
Counter value: 1
Counter value: 2
Counter value: 3