DEV Community

Sasireka
Sasireka

Posted on

Static and Non-Static Variables in Java

  • In Java, variables are mainly categorized into two main types based on their working and memory allocation, and these two variables are static variables and non-static variables.

  • Static variables: These are variables that are shared among all the instances of a class.

  • Non-static variables: These are variables that belong to each individual instance of a class.

Static Variables (Class Variables)

  • Declared with the static keyword, these variables belong to the class itself rather than any specific instance.

  • Example:

public class Home{
    static String Department = "Computer Science";
    static int Mark = 87;
    public static void main(String[] args){
        System.out.println(Home.Department);
        System.out.println(Home.Mark);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Non-Static Variables (Instance Variable)

  • Non-static variables are declared without the static keyword and belong to individual objects.

  • Example:

public class Non_Static{
    String Department = "Computer Science";
    int Mark = 87;
    public static void main(String[] args){
        Non_Static Details = new Non_Static();
        System.out.println(Details.Department);
        System.out.println(Details.Mark);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)