×

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be used with variables, methods, blocks, and nested classes. The static keyword refers to a class rather than a particular instance of the class. A static method belongs to a class but not to an instance of that class and so may be called without the class's instance or object. A static method always starts with a Static Keyword.

The following code is an example of a static method.

StaticExample.java

public class StaticExample {
   //Static variable
   static String name = "Sahil is the Writer of this Article";  
    static void display()                              //Static  method
    {
        System.out.println("Hello Everyone");
    }
    public static void main(String[] args) {
        display();     
//calling the method without creating its object
    System.out.println(name);            
 // calling the static variable
    }
}

Output:

Static Vs Non-Static In Java

Every method in Java defaults to a non-static method if it doesn't have the static keyword before it. Non-static methods can access every static method and static variable without creating an instance of the object. Dynamic or runtime binding is utilized with non-static methods. We may override the non-static method, unlike the static method. Following is an example of a non-static method.

public class Example {
    public void display()                     // non static method
    {
        System.out.println("This method is a non-static method with public as its access speciifer");
    }


    private  void  display2()           // non static method
    {
        System.out.println("I hope you can now differentiate between Static and Non-Static Method");


    }


    String name = "Sahil Deshmukh";                     // non static variable
    static String Autor = "Name of the Author";        // static method
    static void display1()                            // static method
    {
        System.out.println("Have a good day");
    }


    public static void main(String[] args) {


        Example e = new Example();


        System.out.println(Autor);                 // printing a static variable
        System.out.println(e.name);               //  printing a non-static variable
        System.out.println();
        e.display();
        e.display2();


        display1();


    }


}

Output:

Static Vs Non-Static In Java

As you can observe, no instance was created to call a static method, whereas to call a non-static method first, we need to create a class instance and then call the particular method.

The following table summarizes the differences between the above methods

Static MethodNon-Static Method
A static method belongs to a class but not to an instance of that class and may therefore be called without needing the class's instance or object.Every method in Java defaults to a non-static method if it doesn't have the static keyword before it. Non-static methods may access every static method and static variable without using the class object.
Only static data members and methods of other classes or the same class may be accessed by the static method; non-static methods or variables are not accessible.The non-static method can access both static data members and static methods and non-static members and methods from the same or another class.
Compile-time or early binding is used in the static technique.Runtime or dynamic binding is used in the non-static technique.
Because of early binding, the static method is not overridable.Because of runtime binding, the non-static method can be altered.
The static approach uses less memory for execution because memory allocation occurs just once because the static keyword provided a specific memory address in ram for that operation.The non-static method consumes a lot of memory during execution since memory is allocated when the method is called, and memory is allocated every time the method is called.

The static and non-static approaches were described in the preceding article, as it discussed the methods and their implementation. Let's take a closer look at static and non-static variables now.

A variable is a container that retains the value while a program, such as a Java application, is running. A variable is allocated with a data type. The term "variable" refers to a memory region's name. In Java, there are three types of variables:

  • Static Variables
  • Local Variables
  • Instance Variables

Non-Static variables are a combination of local variables and instance variables. As a result, it's possible to divide Java variables into two categories:

Static Variables

When a variable is declared static, a single copy of it is made and shared among all objects in the class. Static variables, on the other hand, are effectively global variables. It's a class-specific variable, not an object-specific variable. All instances of the class share the static variable. A static variable may be accessed simply by the class name and does not need the use of an object. It improves the memory efficiency of your software (i.e., it saves memory).

// Example of static variable
public class Example1 {
    static String name ="Sahil";          //Static Variable
    public static void main(String[] args) {
        System.out.println(name);
    }
}

Output:

Static Vs Non-Static In Java

Local Variables

  • A local variable is a variable declared within a block, method, or function.
  • These variables are generated when the block is entered, or the function is called, and they are removed when the block or function call returns.
  • These variables have a scope that is limited to the block in which they are defined, i.e., these variables can only be accessed within that block.
  • The initialization of a local variable is required.
public class Example1 {
   void author()
   {
       String  name  ="Sahil Deshmukh";   // local variable
       System.out.println(name);
   }
    public static void main(String[] args) {


        Example1 e = new Example1();
        System.out.println("Name of the Author");
       e.author();
    }
}

Output:

Static Vs Non-Static In Java

Instance Variables

  • These are non-static variables defined outside of any method, constructor, or block of a class.
  • When a class declares instance variables, these variables are produced when the class's object is formed and deleted when the object is destroyed. For instance, unlike local variables, variables can utilize access specifiers. The default access specifier will be utilized if no access specifier is provided. It is not necessary to initialize the instance variable. It has a value of 0 by default. Only by constructing objects can you access the Instance Variable.
  • In contrast to local variables, we can utilize access specifiers on instance variables. The default access specifier will be utilized if no alternative access specifier is supplied.
  • An instance variable does not need to be initialized. By default, the value is set to 0.
  • Instance Variable can only be accessed by creating objects.
// Example of Instance variable
public class Example1 {
    String  name  ="Sahil Deshmukh";          //instance variable
    public static void main(String[] args) {
        Example1 e = new Example1();
        System.out.println("Name of the Author");
        System.out.println(e.name);
    }
}

Output:

Static Vs Non-Static In Java

Local Vs. Instance Vs. Static Variable

The following table summarizes the difference between all these three variables

Local VariableInstance VariableStatic Variable
Within a procedure or a code block, a variable is defined.At the class level, defined outside of a method.At the class level, defined outside of a method.
It can only be accessed in the method/code block where it was declared.Is available at all times throughout the class.Is available at all times throughout the class
As long as the procedure is running, it stays in memory.As long as the thing is remembered, it will remain in memory.As long as the application is running, it stays in memory.
There is no need for a unique keyword.No particular keyword is required; however, any access specifier (private, protected, or public) can be supplied. Typically, the terms private and protected are employed.It is necessary to use the static keyword. You can also specify any access specifier (private, protected, or public). The term "public" is frequently used.
It must be initialized before it can be utilized.Because it has a default value depending on its data type, it doesn't need to be initialized before use.Because it has a default value depending on its data type, it doesn't need to be initialized before use.

Related Topics

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.