The great Static Keyword in Java
2 min readMay 14, 2024
Purpose of the Static Keyword:
- The static keyword in Java helps optimise memory usage by creating variables, methods, and blocks that are shared across multiple instances of a class.
Creating Static Variables:
- Without static: Each instance of a class would have its own copy of the variable, consuming memory.
- With static: Variable’s value remains constant across all instances, saving memory.
- Example:
class Student {
String studentName;
String course;
static String school;
}
Example of Static Variables:
- Without static keyword:
Student Student1 = new Student();
Student1.school = "JapneetSachdeva";
- With static keyword:
Student1.school = "JapneetSachdeva";
Static Methods:
- Can only access and modify static variables.
- Can be called without creating a class instance.
- Example:
static void incrementBy2()
{
evenNumber = evenNumber + 2;
System.out.println(evenNumber);
}
Static Blocks:
- Similar to constructors, used to initialize static variables.
- Executed by the compiler before the main method.
- Example:
static {
year = 2024;
System.out.println("This code block got executed first");
}
Order of Execution:
- Static blocks are executed before the main method.
- Example:
This code block got executed first
Hello World
2024
- Summary:
- The static keyword helps optimise memory usage in Java programs.
- Used for creating static variables, methods, and blocks.
- Static blocks initialise static variables and are executed before the main method.
- For Test Automation, Use Static Keyword only for reusable methods. Overuse of static can drop the advantages of OOP.
-x-x-
If you are targeting to into Automation Testing roles, then take a look at my course: Link
SDETs interview prep material with coding Q&A, Input/Output etc. : Link
Follow me on LinkedIn here: https://www.linkedin.com/in/japneet-sachdeva/
#japneetsachdeva