Java Static Keyword
Syntax
static variable;
static method();
static block;
Example
public class MyClass {
static int num = 10;
public static void main(String[] args) {
System.out.println(num);
changeNum();
System.out.println(num);
}
static void changeNum() {
num = 20;
}
}
Output
10
20
Explanation
In Java, the static
keyword can be used to declare variables, methods, and blocks as static. A static
variable or method belongs to the class itself, instead of to any particular instance of the class. This means that you can access the variable or method directly from the class, without having to create an instance of the class first.
In the example above, we have a static variable num
and a static method changeNum()
. In the main()
method, we first print the value of num
(which is 10
), then call changeNum()
to change the value of num
to 20
, and finally print the new value of num
(which is 20
).
Use
The static
keyword is used in Java to create class-level variables and methods that can be accessed without creating an instance of the class. This can be useful in many situations, such as when you need to keep track of a global variable throughout your program, or when you have a utility class that contains only static methods.
Important Points
- Static variables and methods belong to the class itself, not to any particular instance of the class.
- You can access static variables and methods directly from the class, without having to create an instance of the class first.
- You can also use static blocks to initialize static variables.
Summary
In Java, the static
keyword is used to create class-level variables and methods. These can be accessed directly from the class, without creating an instance of the class first. Static variables and methods are useful in many situations, such as when you need to keep track of a global variable throughout your program, or when you have a utility class that contains only static methods.