DEV Community

S Sarumathi
S Sarumathi

Posted on

Static and Non-Static

1. What is Static in Java?
- A static variable or method belongs to the class, not to objects.

  • This means only one copy exists and all objects share it.

  • To call a static method, it is not necessary to create an object.

Example:


class Student {
    static String college = "ABC College";
    String name;
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student();

        System.out.println(Student.college);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

ABC College
Enter fullscreen mode Exit fullscreen mode

Why Use Static?

  • Because college name is same for all students, we don't need multiple copies.

  • So Java creates only one memory location.

2. What is Non-Static in Java?
- A non-static variable belongs to object.
- Each object gets separate memory.
- To call a non-static method, an object must be created.

Example:

class Student {
    String name;
}

public class Main {
    public static void main(String[] args) {

        Student s1 = new Student();
        s1.name = "Ram";

        Student s2 = new Student();
        s2.name = "Sam";

        System.out.println(s1.name);
        System.out.println(s2.name);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Ram
Sam
Enter fullscreen mode Exit fullscreen mode

Why Non-Static?

  • Because each student has different name,

  • so each object needs separate memory.

Top comments (0)