+ 10
Use of Static block, Static variable and Static method?
Can anyone please explain me the purpose of using static variable , static method and static blocks in Java
2 Answers
+ 15
â Static variable
It gets memory once when it is declared inside a class[it is accessible in static methods I make so i can make changes to its value directly from any method , that is the major advantage ]
â Static methods
you can call them without creating objects of that class [haha it saves time]
â Static block
The statements of the static block gets executed before the main method [I don't use it generally in my challenges codes though U can see use of it ]
+ 2
The important thing to note about static block is that it runs before main() method and does not require any invoking statement.This block is used to initialize static variables
static variables are declared within a class but outside methods using the keyword static.Once declared, it can be used anywhere within the class in which it is declared. In other words it can be used as a global variable within the class in which it is declared.
static methods are declared within a class using the keyword static
https://code.sololearn.com/c7mUhrUEf6qw/?ref=app
go through the code and see the comment