×

Difference between Static and Instance Methods in Java

Static Method in Java

The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of the occasions of a similar class, and they are gotten to by the class name of the specific class. A static catchphrase is utilised for proclaiming the static technique in java. The static methods are examined in subtleties further in the article. The static techniques are the class strategies and don’t have a place with class cases. These are intended to be divided between every one of the cases of a similar class, and they are gotten to by the class name of the specific class. A static watchword is utilised for pronouncing the static technique in java.

The static technique in java can't be superseded because static strategies are connected to the class during the gathering time, and we know very well that strategy abrogating depends on the runtime polymorphism, which is why the static techniques can't be superseded. The external climate can quickly get the static methods without any problem.

Syntax:

//static keyword must be used for the static methods
static return_type method name(parameter)
{
//here, we write the Code to be executed
}

The return_type of the static method can be int, float, or any user-defined datatype.

Declaration of Static Method in Java

The statement of the static technique or method is like the announcement of the example strategy; however, on account of the static technique or method report, we need to utilise a static watchword before the information of a system.

Example:

class SM{
    static void print(){
        System. out.println("This is the static method of the SM class");
    }
   }

The print() technique for the class Scaler is of a static sort, and we don't need an example of the class to get to it.

How to call Static Method:

We can call the static techniques with the assistance of the class name since they have a place with the actual class, and they have no connection with the occurrences of the class.

Syntax:

ClassName.methodName()

The class name in the above syntax represents the name of the present class followed by the method name given in the program.

Example:

class SM {
    static void print() 
   {
        System. out.println("This is the static method of the SM class");
    }
    public static void main(String[] args) 
   {
        SM.print();
    }
}

Output:

This is the static method of the SM class

Uses of Static method:

This question generally emerges in the psyche of the software engineer when involving a static technique in java programs. We can use the static method in our group when we know the legitimate utilisation of the fixed strategy. We should see some regular use for static techniques with the goal that we can proficiently utilise them.

  •  At the point when the execution of the specific method isn't subject to the occurrence factors and example strategies, For this situation, we can make that strategy to be static.
  • If the class cases don't change the execution of the system’s code. For this situation, we can make the technique a static strategy.
  • If we desire to characterise a few utility capabilities, for example, a client represented arranging strategy in the class, we can describe them utilising static ideas since the utility capability can undoubtedly be divided between all objects of the course because of the property of the static strategy.

Restrictions of Static Method:

When the strategies are announced as static, there are loads of limitations applied to the static method that makes it not quite the same as the case techniques for the class.

  • The static strategy can't conjure the case part and techniques for the class. Since static methods are gotten to without the class item reference, we can't get to the occasion factors and strategy without an article reference. This will cause a blunder if we attempt to get to the case variable or system inside the static technique.
  • The static techniques can get to just other static individuals and strategies. Since static individuals and methods are connected to the class during the aggregation time, they can get to one another without making the case of the course.
  • We can’t involve this, and super watchword in the body of the static strategy since this catchphrase is the reference of the ongoing item. Yet, without making an article, we can get to the static technique; this will cause a blunder; on account of the super watchword, we realise very well that super is the reference of the parent class; however, we can't involve contact in that frame of mind of the static technique. We have proactively talked about the explanation for this.

Important Points to Remember:

  • The static techniques are the class strategies and are gotten to by the name of the class.
  • The static techniques can't be abrogated because fixed strategies are settled at the aggregation season of the java program; we realise very well that the method superseding is the runtime polymorphism.
  • The watchwords, for example, super, can't be utilised in that frame of mind of the static technique; we have proactively discussed this purpose in the above segment.
  • The static techniques can't get to the case individuals and strategies for the class.
  • The condition of the static techniques is similarly divided between every one of the class objects.

Example:

//simple Java program to demonstrate that in static and non-static methods, //static methods are directly accessed.
import java.io.*;
public class SM {
    static int n = 100;
    static String s = "Vijay";
    // This is a Static method
    static void display()
    {
        System.out.println("The given static number is: " + n);
        System.out.println("The given static string is: " + s);
    }
    //here, we are declaring the non-static method
    void nonstatic()
    {
        //The static method can be accessed in the non-static method
        display();
    }
    //here, we are declaring the primary method
    public static void main(String args[])
    {
        SM b = new SM();
        // This is the object(b) to call non static function
        b.nonstatic();   
        //The static method can be called directly without an object
        display();
    }
}

Output:

The given static number is: 100
The given static String is: Vijay
The given static number is: 100
The given static String is: Vijay

Instance Method in Java:

Occasion Techniques are the gathering of codes that plays out a specific undertaking. Sometimes the program fills in size, and we need to isolate the rationale of the principal technique from different strategies. A technique is a capability composed inside the class. Since java is an item-situated programming language, we want to compose written inside certain classes.

The significant focuses with respect to occurrence factors are:

  • Occurrence strategies can get to example factors and occasion techniques straightforwardly and undeviatingly.
  • Case strategies can get to static factors and static techniques straightforwardly.

Instance Method without parameter:

Syntax:

modifier return_type method name( )
{
        method body ;
}
  • modifier: It characterises the entrance sort of the technique, and it is discretionary to utilise.
  • return_type: Strategy might return a worth. Ex:- int, void, String, singe, float, and so forth.
  • method_name: This is the strategy name. You can compose anything as you compose the variable name.
  • method body: The strategy body depicts how the strategy manages explanations.

Example:

public void cry( )
{
       int n = 40;
    System.out.println(n);
}

How to call the instance method:

You can not call an occurrence technique in the static strategy straightforwardly so that the Example strategy can be conjured utilising an object of the class. We realise that the java program's execution begins from the principal technique and the primary strategy is static, so we can not call the case technique straightforwardly. We need to make the class object; then, at that point, we can call the example strategy in the fundamental technique.

Example:

//simple java program to understand how to call the instance method into our //program without parameters
import java.io.*;                 //importing the java input-output standard package into //the program
  
class IM {            //creating the class with the name IM
      //here, we are creating the static method static method
    public static void main (String[] args) {  
          // Creating the object for the IM class
        IM n = new IM();          
          //here, we are Calling the instance method
        n.show();  
        System. out.println("welcome to the Instance method");
    }
      //here, we are calling the Instance method
    void show()        //creating the method with the name show                          
    {
          //here, we are declaring the Local variables
        int a = 55;            //creating the integer variable with some data                   
        System. out.println(“The given integer value is:”+a);         //printing the integer //data that is assigned above
    }
}

Output:

The given integer value is: 55
Welcome to the Instance method

Example 1:

//simple java program to understand how to call the instance method into our //program without parameters and to perform addition
import java.io.*;                 //importing the java input-output standard package into //the program
//here, it is a different class for methods
class A {      //creating the class with the name A
    //creating the Instance method in the different class 
    void add()                
    { 
      int i = 36;     //creating the integer variable I with the value 36
      int j = 24;     //creating the integer variable j with the value 24
      System.out.println("The sum of the given two numbers is:" + (i+j));
    }
}
class IM {
      //creating the Static method
    public static void main (String[] args) {        
          // creating the object for the class IM
        A n = new A();                     
          //here, we are calling the instance method
        n.add();              
        System. out.println("addition operation performed successfully");
    }
}

Output:

The sum of the given two numbers is: 50
Addition operation performed successfully

Instance Method With Parameter:

The instance method with parameter takes the arguments when we call the method from the main method.

Syntax:

modifier return_type method name( parameter list)
{
    method body ;
}

The comma separates the parameters.

Example:

public void add(int i, int j)
{
      int a = i ;
      int b = j;
      int c = a+b;
     System.out.println(c);
}

Example 1:

//simple java program to understand how to call the instance method into our //program with parameters and to perform addition
import java.io.*;                 //importing the java input-output standard package into //the program
class IM {
      //creating the static method
    public static void main (String[] args) {        
          //creating the object for the class IM
        IM n = new IM();                   
         //here, we are calling the instance method by passing the values
        n.add(24, 36);       
        System. out.println("Addition operation performed successfully");
    } 
  //creating the Instance method with parameter
  void add(int i, int j)          
  { 
    //here, we are creating the local variables
    int a = i;             //declaring a integer variable a with some data       
    int b = j;             //declaring a integer variable b with some data
    int c = i +j;          //declaring a integer variable c which performs addition of two //numbers       
    System. out.println("The Sum of the given numbers is: " + c);
  }
} 

Output:

The Sum of the given numbers is: 50
Addition operation performed successfully

Types of Instance Methods:

The instance method is categorised into two types:

  • Accessor Method (Getters):
    The accessor technique is utilised to make the code safer and increment its insurance level, and the accessor is otherwise called a getter. Getter returns the worth (accessors); it returns the value of information type int, String, twofold, float, and so on. For the accommodation of the program, the getter begins with "get" trailed by the variable name.
    An Accessor strategy is generally known as a getting technique or a getter. The accessor strategy returns a property of the item. They are announced as open. Accessors trail a naming plan; as such, they add a word to get to the beginning of the strategy name. They are utilised to return the worth of a confidential field.
  • Mutator Method (Setters):
    The mutator technique is otherwise called the setter. It sets the incentive for any factor utilised in a class’s projects. What’s more, it begins with "set" trailed by the variable name. Getter and Setter make the developer helpful in setting and getting the incentive for a specific information type. In both getter and setter, the principal letter of the variable ought to be capital.
    A Mutator strategy is commonly known as a set technique or just a setter. A Mutator technique transforms things, all in all, change something. It shows us the standard of embodiment. They are otherwise called modifiers. They are effortlessly spotted because they begin with the word set. They are announced as open. Mutator strategies have no return type and acknowledge a boundary of similar information type contingent upon their confidential field.
  • Accessor and mutator are used to access or set the incentive for the confidential individual from the class in the principal strategy.

Example:

//simple Java program to demonstrate the types of instance methods  
import java.io.*;       //importing the java input-output standard package into the //program
class TIM{           //creating the class with the name TIM
      //here, we are declaring the private variable with some data
    private int a = 250; 
      //here, we are using one type of Instance method accessor method (getter)
    public int getnum()
    { 
        return a;        //it will directly return the value of a
    }      
      // here, we are using one type of Instance method Mutator method (setter)
      public void setnum(int b)        //passing the parameters
    { 
          //here, we will increment the given value by b and return the number + b;
        a += b;
    }
}
class IM {       //creating the class with the name IM
    public static void main(String[] args)
    {
        TIM m = new TIM();
          //here, we are setting a new value for the number
        m.setnum(400);   
          //here, we are calling the Mutator method(accessor)
        System. out.println("The number after performing all operations is: "+ m.getnum());                                  
        System.out.println("successfully performed the different types of Instance methods");
    }
}

Output:

The number after performing all the operations is: 650
Successfully performed the different types of Instance methods

Difference between Static and Instance methods:

Static method:

  • Static strategies can be called without the object of the class.
  • Static strategies are related to the class.
  • Static strategies can get to static credits of the class
  • A static strategy is pronounced with the static catchphrase.
  • The static strategy will exist as a solitary duplicate for a class.
  • Static strategies can get to the static factors and static techniques straightforwardly.
  • Static techniques can't get to Instance strategies and example factors straightforwardly. They should utilise references to protest. What's more, the static technique can't involve this catchphrase as there is no occurrence for 'this' to allude to.

Instance method:

  • Instance techniques require an object of the class.
  • Instance strategies are related to the items.
  • Instance strategies can get to every one of the qualities of the class.
  • Instance strategies require no catchphrase.
  • The Instance strategy exists as various duplicates relying upon the number of examples of the class.
  • The instance technique can easily get to the case strategies and occurrence factors.
  • Instance strategy can get to static factors and static techniques straightforwardly.

Related Topics

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Difference between = = and equals ( ) in java

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...

6 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 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 String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.