static
keyword is a non-access modifier in Java.
static
keyword:
static
member is shared among all objects of the class.
class Student
{
String name;
int rollNo;
static String schoolName = "ABC Public School"; // static variable shared by all students
// Constructor
Student(String name, int rollNo)
{
this.name = name;
this.rollNo = rollNo;
}
// Method to display student details
void displayDetails()
{
System.out.println("Name : " + name);
System.out.println("Roll No : " + rollNo);
System.out.println("School : " + schoolName);
System.out.println("--------------------------");
}
}
public class StaticDemo
{
public static void main(String[] args)
{
// Creating student objects
Student s1 = new Student("Amit", 101);
Student s2 = new Student("Deepak", 102);
Student s3 = new Student("Rahul", 103);
// Displaying student details
s1.displayDetails();
s2.displayDetails();
s3.displayDetails();
}
}
Name : Amit Roll No : 101 School : ABC Public School -------------------------- Name : Priya Roll No : 102 School : ABC Public School -------------------------- Name : Rahul Roll No : 103 School : ABC Public School --------------------------
public class Counter
{
// static variable to keep count of objects
static int count = 0;
// Constructor
Counter()
{
count++; // Increment static counter
System.out.println("Object created. Count = " + count);
}
public static void main(String[] args)
{
// Creating objects
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
}
}
Object created. Count = 1 Object created. Count = 2 Object created. Count = 3
public class StaticDemo
{
// Static method
static void greet()
{
System.out.println("Hello! This is a static method.");
}
// Non-static method
void showMessage()
{
System.out.println("This is a non-static method.");
}
public static void main(String[] args)
{
// Calling static method directly without creating an object
greet();
// Calling non-static method requires an object
StaticDemo obj = new StaticDemo();
obj.showMessage();
}
}
Hello! This is a static method. This is a non-static method.
public class StaticDemo
{
static int maxLimit;
static
{
maxLimit = 100; // static block for initialization
System.out.println("Static block executed.");
}
public static void main(String[] args)
{
System.out.println("Max Limit : "+maxLimit);
System.out.println("Main method executed");
}
}
Static block executed. Max Limit : 100 Main method executed
public class Outer
{
// Static nested class
static class Inner
{
void show()
{
System.out.println("Static nested class method.");
}
}
public static void main(String[] args)
{
// Creating an object of the static nested class
Outer.Inner obj = new Outer.Inner();
obj.show();
}
}
Static nested class method.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.