Open links in new tab
  1. In Java, variables can be classified into two main types: static variables and instance variables. Understanding the difference between these two types is crucial for effective Java programming.

    Static Variables

    Static variables are also known as class variables. They are declared using the static keyword and belong to the class rather than any specific instance of the class. This means that all instances of the class share the same static variable. When a static variable is modified, the change is reflected across all instances of the class.

    Example:

    public class Test {
    public static int a = 5; // Static variable
    public int b = 10; // Instance variable
    }

    Test t1 = new Test();
    Test t2 = new Test();

    System.out.println(t1.a); // Output: 5
    System.out.println(t2.a); // Output: 5

    t1.a = 20;

    System.out.println(t1.a); // Output: 20
    System.out.println(t2.a); // Output: 20

    In this example, changing the value of a in one instance (t1) affects the value of a in the other instance (t2) because a is a static variable.

    Feedback
  1. Some results have been removed
Refresh