Accessing Static Members in Java Classes

Day 19 – How to Access Static Members of a Class in Java? In Java, static members belong to the class, not to objects. That means 👇 You don’t need to create an object to access them. 🔹 Syntax ClassName.memberName; Simple. Direct. Object not required. 🔹 Example 1 – Accessing Static Variables & Methods class Demo1 { static int x = 100; static int y = 200; static void test() { System.out.println("running test() method"); } } class Demo2 { public static void main(String[] args) { System.out.println("x=" + Demo1.x); System.out.println("y=" + Demo1.y); Demo1.test(); } } 🔹 Output: x=100 y=200 running test() method Notice: We accessed everything using ClassName.memberName. 🔹 Example 2 – Modifying Static Variables class Demo3 { static int x = 100; static int y = 200; } class Mainclass1 { public static void main(String[] args) { System.out.println("x=" + Demo3.x); System.out.println("y=" + Demo3.y); System.out.println("Modifying x & y"); Demo3.x = 300; Demo3.y = 400; System.out.println("x=" + Demo3.x); System.out.println("y=" + Demo3.y); } } 🔹 Output: x=100 y=200 Modifying x & y x=300 y=400 ⚠ Important Concept 👉 static ≠ constant A static variable: Belongs to the class Is shared among all objects Can be modified If you want a constant, use: static final int VALUE = 100; #Java #CoreJava #JavaFullStack #LearningInPublic #Programming #BackendDevelopment

To view or add a comment, sign in

Explore content categories