Static Members in Java

 

🔷 Static Members in Java

✅ What is static in Java?

The static keyword in Java is used for memory management. It makes a member (variable or method) belong to the class rather than an instance of the class.


📌 Types of Static Members:

  1. static variables (class variables)

  2. static methods

  3. static blocks

  4. static nested classes


✅ 1.1 Static Variable

  • Shared among all objects of a class.

  • Stored in method area (not heap).

  • Initialized only once at class loading time.

🔹 Example:


class Student { int rollNo; static String college = "ABC College"; // static variable Student(int r) { rollNo = r; } void display() { System.out.println(rollNo + " - " + college); } } public class Main { public static void main(String[] args) { Student s1 = new Student(101); Student s2 = new Student(102); s1.display(); s2.display(); } }

✅ Output:

101 - ABC College
102 - ABC College

✅ 1.2 Static Method

  • Can be called without creating an object.

  • Can only access static data directly.

  • Cannot use this or super.

🔹 Example:

class MathUtils {
static int square(int x) { return x * x; } } public class Main { public static void main(String[] args) { System.out.println(MathUtils.square(5)); // no object needed } }

✅ 1.3 Static Block

  • Used to initialize static variables.

  • Runs once when the class is loaded.

🔹 Example:

class Demo {
static int x; static { x = 10; System.out.println("Static block initialized."); } static void show() { System.out.println("x = " + x); } } public class Main { public static void main(String[] args) { Demo.show(); } }

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Java Compiler and Java Virtual Machine