Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Difference between Static and Non-Static Variables in Java

Last Updated on March 2, 2023 by Prepbytes

Static and Non Static Variables are two different types of variables in Java.
Static variables are shared by all objects of a class and have a single instance, while non-static variables are unique to each object and have different values for different objects.

Let us first learn about the Static Variables and Non-Static Variables, before discussing the major differences between Static and Non Static in Java.

Static Variables in Java

Static variables in Java are class-level variables that are shared among all objects of a class. They are declared using the "static" keyword and are stored in the class area. Because they are shared, their values can be accessed and modified by any object of the class. They are also known as class variables.

Static variables are typically used to represent class-level data, such as the number of instances of a class that have been created, the maximum value allowed for a particular property, or a default value for a property.

The static variables are initialized only once when the class is loaded and their values persist throughout the life cycle of the class.

Syntax for declaring Static Variables in Java:

accessSpecifier static dataType variableName;

Here’s an example of declaring a static integer variable named count:

public static int count;

In this example, public is the access specifier, int is the data type, and count is the name of the static variable. The static keyword is used to specify that this is a static variable.

It is also possible to initialize a static variable when it is declared, like this:

public static int count = 0;

In this example, the static variable count is initialized to the value 0 when it is declared.

Examples of Static Variables in Java

Here are some examples for a deep understanding of the Static Variables in Java:

Example 1: Counter Program in Java using Static Variables
The value of the static variable remains the same across all the objects. The below Java code explains it in a neater way.

class Example {
  static int count = 0;

  public Example() {
    count++;
  }

  public static void main(String[] args) {
    Example obj1 = new Example();
    Example obj2 = new Example();
    Example obj3 = new Example();

    System.out.println("Number of objects created: " + Example.count);
  }
}

Output:

Number of objects created: 3

Explanation:
In this example, count is a static variable that keeps track of the number of Example objects that have been created. Each time a new Example object is created, the value of count is incremented. Since count is a static variable, its value is shared across all Example objects and can be accessed directly via the class name (Example.count), rather than via an instance of the class.

Example 2: Area of Circle Program in Java using Static Variables
The value of the static variable remains the same across all the objects. It can be used to declare constant such as pi, M, etc. in the Java Code.

class Circle {
  static double pi = 3.14;

  double radius;

  public Circle(double r) {
    radius = r;
  }

  public double area() {
    return pi * radius * radius;
  }

  public static void main(String[] args) {
    Circle c1 = new Circle(5);
    Circle c2 = new Circle(7);

    System.out.println("Area of circle 1: " + c1.area());
    System.out.println("Area of circle 2: " + c2.area());
  }
}

Output:

Area of circle 1: 78.5
Area of circle 2: 153.86

Explanation:
In this example, pi is a static variable that is used to store the value of pi, which is a constant. Since the value of pi is the same for all circles, it makes sense to declare it as a static variable so that it can be shared across all instances of the Circle class. The radius instance variable, on the other hand, is unique to each individual Circle object and is therefore declared as a non-static (or instance) variable.

Non-Static Variables in Java

Non-static variables in Java are also known as instance variables. They are defined within a class but not marked as static. Unlike static variables, non-static variables are associated with an instance of a class and are stored in heap memory. This means that each object of the class will have its own copy of the non-static variables.

Non-static variables are used to represent object-level data and are typically used to store data that is unique to each instance of a class. They can be accessed and modified using object references.

The non-static variables are created each time an object is created and are destroyed when the object is garbage collected. Their values can be changed at any time during the life cycle of the object.

Syntax for declaring Non-Static Variables in Java:

Non-static (also known as instance) variables in Java are declared using the following syntax:

accessSpecifier dataType variableName;

Here, access modifier can be any of public, private, protected, or omitted (default). Data type is the type of the variable, such as int, String, etc. The variable name is the name you choose for the variable.

Here’s an example to show the syntax and declaration of static variable in Java:

private int count;
public String name;
float balance;

Example of Non-Static Variables in Java

Non-static (also known as an instance) variables in Java are specific to a single instance of a class and can hold different values for each object of the class.

Here is an example of how to declare and use non-static variables in Java:
Example: BankAccount Class with Non-Static Variables in Java
We will see the initialization on Non-Static Variables as per the syntax discussed above in the following code:

class BankAccount {
    private int accountNumber;
    private String accountHolderName;
    private double balance;

    public BankAccount(int accountNumber, String accountHolderName, double balance) {
        this.accountNumber = accountNumber;
        this.accountHolderName = accountHolderName;
        this.balance = balance;
    }

    public int getAccountNumber() {
        return accountNumber;
    }

    public String getAccountHolderName() {
        return accountHolderName;
    }

    public double getBalance() {
        return balance;
    }
}

class Main{
    public static void main(String args[]){
        BankAccount account1 = new BankAccount(12345, "John Doe", 5000.0);
        BankAccount account2 = new BankAccount(67890, "Jane Doe", 6000.0);

        System.out.println("Account Number: " + account1.getAccountNumber());
        System.out.println("Account Holder Name: " + account1.getAccountHolderName());
        System.out.println("Balance: $" + account1.getBalance());

        System.out.println("Account Number: " + account2.getAccountNumber());
        System.out.println("Account Holder Name: " + account2.getAccountHolderName());
        System.out.println("Balance: $" + account2.getBalance());

    }
}

Output:

Account Number: 12345
Account Holder Name: John Doe
Balance: $5000.0
Account Number: 67890
Account Holder Name: Jane Doe
Balance: $6000.0

Explanation:
In this example, the BankAccount class has three non-static variables: accountNumber, accountHolderName, and balance. Each instance of the class will have its own unique values for these variables. The class has a constructor method that takes these values as arguments and assigns them to the corresponding variables using the this keyword. The class also has getter methods to retrieve the values of these variables. In the main method, we create objects of the BankAccount class and assign values to their instance variables.
Each object of the BankAccount class has its own unique values for the accountNumber, accountHolderName, and balance variables because of the non-static nature of variables.

Let us now discuss the difference between Static and Non Static in Java in detail.

Difference between Static and Non Static Variables in Java

In Java Programming Language, the Static and Non Static variables differ a lot. The table given below summarizes the key differences between the static and non static variables in Java:

Feature Static Variable Non-Static Variable
Definition A static variable is a variable that is declared using the static keyword. A non-static variable is a variable that is not declared using the static keyword.
Memory Allocation Allocated in class area and shared among all objects. Allocated in heap memory and created for each object.
Access Can be accessed using class name. Can be accessed using object reference.
Scope Scope is limited to the class. Scope is limited to the object.
Initialization Initialized only once when the class is loaded. Initialized each time an object is created.
Usage Used to represent class-level data. Used to represent object-level data.
Example public static int count = 0; public int age;
Inheritance Can be inherited by the subclass. Cannot be inherited by the subclass.
Modification Can be modified using class name. Can be modified using object reference.
Usage in Method Can be used in both static and non static in java. Can be used only in non-static methods.
Life Cycle It is created when the class is loaded and destroyed when the class is unloaded. It is created when the object is created and destroyed when the object is garbage collected.

Conclusion
We have covered the static and non static variables in Java in detail. Variables and methods in Java are non-static by default, but the main() function is static in nature. The static keyword can be used to manage memory. In contrast to non-static methods, which cannot be used without constructing an object, static methods may be made available without generating an object. With the help of explanations and examples, we have discussed static and non static variables and methods in Java.

Let us go through some of the Frequently Asked Question on Static and Non Static in Java.

Frequently Asked Questions (FAQs)

Q: When to use static variable in Java?
A: Use static variable in Java when you want to share the same value across all instances of a class, for example, a constant or a counter shared by all instances.

Q: When to use non-static variable in Java?
A: Use non-static variable in Java when you want to store instance-specific data, for example, instance-specific attributes or variables with different values for different instances.

Q: How to access static and non-static variables in Java?
A: You can access static variables using the class name followed by the dot operator (.) and the variable name. Non-static variables can be accessed using an instance of the class followed by the dot operator (.) and the variable name.

Leave a Reply

Your email address will not be published. Required fields are marked *