Java Static Keyword:
In Java, the static keyword is used to define class-level variables and methods that can be accessed without creating an instance of the class. Here are some key characteristics of the static keyword in Java:
public class Example {
static int count = 0;
}
In this example, we define a class-level variable called count. We can access this variable using the class name:
int x = Example.count;
public class Example {
static void printMessage() {
System.out.println("Hello, world!");
}
}
In this example, we define a static method called printMessage. We can call this method using the class name:
Example.printMessage();
public class Example {
static {
System.out.println("This is a static block.");
}
}
In this example, we define a static block that prints a message to the console when the Example class is loaded into memory.
Here is an example that shows the use of static variables and methods in Java:
public class Example {
static int count = 0;
static void incrementCount() {
count++;
}
public static void main(String[] args) {
Example.incrementCount();
Example.incrementCount();
Example.incrementCount();
System.out.println("Count is: " + Example.count);
}
}
In this example, we define a class-level variable called count and a static method called incrementCount that increments the count variable. We call the incrementCount method three times and then print the value of count to the console. The output of this program would be:
Count is: 3
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.