09 Static Keyword in Java
09 Static Keyword in Java
examples.
ANS:
➢ The static keyword in Java is mainly used for memory management.
➢ The users can apply static keywords with variables, methods, blocks, and
nested classes.
➢ When a member is declared as static, it means that it belongs to the class itself
rather than to instances (objects) of the class.
➢ Static members are associated with the class, not with individual
objects.
➢ This means that changes to a static member are reflected in all
instances of the class, and that you can access static members
using the class name rather than an object reference.
Cannot access non-static members:
❖ ADVANTAGES:
Memory efficiency: Static members are allocated memory only once
during the execution of the program, which can result in significant
memory savings for large programs.
Constants: Static final variables can be used to define constants that are
shared across the entire program.
➢ They are executed only once when the class is loaded into memory,
before the execution of the main method or creation of any object of
that class.
// Static block
static
{
System.out.println("Static block is initialized.");
➢ Static variables are, essentially, global variables. All instances of the class
share the same static variable.
Important points for static variables:
• We can create static variables at the class level only.
• static block and static variables are executed in the order they are
present in a program.
Example:
class MyClass
{
// Static variable
static int count = 0;
MyClass()
{
count++; // Increment count each time a new object is created
}
Example:
public class Example
{
// Static variable
static int sVar = 100;
// Instance variable
int iVar = 200;
// Static method
public static void sMethod()
{
System.out.println("Inside sMethod:");
System.out.println("Static variable value: " + sVar);
}
// Instance method
public void iMethod()
{
System.out.println("Inside iMethod:");
System.out.println("Instance variable value: " + iVar);
System.out.println("Static variable value: " + sVar);
}
}
(4)STATIC CLASSES
➢ A class can be made static only if it is a nested class.
➢ Nested static class doesn’t need a reference of Outer class. In this case, a
static class cannot access non-static members of the Outer class.
// Student class
class Student {
String name;
int rollNo;
// static variable
static String cllgName;
// static method
static void setCllg(String name) { cllgName = name; }
// instance method
void getStudentInfo()
{
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);