The Wayback Machine - https://web.archive.org/web/20240905210654/https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
Open In App

Static methods vs Instance methods in Java

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to learn about Static Methods and Instance Methods in Java.

Java Instance Methods

Instance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class in which the method is defined. 

public void geek(String name)
{
 // code to be executed....
}
// Return type can be int, float String or user defined data type.

Memory Allocation of Instance Method

These methods themselves are stored in the Permanent Generation space of the heap (Valid till Java 7 only, now replaced with metaspace from Java 8 and onwards with improved efficiency) but the parameters (arguments passed to them) and their local variables and the value to be returned are allocated in stack. They can be called within the same class in which they reside or from the different classes defined either in the same package or other packages depending on the access type provided to the desired instance method.

Important Points: 

  • Instance method(s) belong to the Object of the class, not to the class i.e. they can be called after creating the Object of the class.
  • Instance methods are not stored on a per-instance basis, even with virtual methods. They’re stored in a single memory location, and they only “know” which object they belong to because this pointer is passed when you call them.
  • They can be overridden since they are resolved using dynamic binding at run time.

Below is the implementation of accessing the instance method:

Java




// Example to illustrate accessing the instance method .
import java.io.*;
 
class Foo {
 
    String name = "";
 
    // Instance method to be called within the
    // same class or from a another class defined
    // in the same package or in different package.
    public void geek(String name) { this.name = name; }
}
 
class GFG {
    public static void main(String[] args)
    {
 
        // create an instance of the class.
        Foo ob = new Foo();
 
        // calling an instance method in the class 'Foo'.
        ob.geek("GeeksforGeeks");
        System.out.println(ob.name);
    }
}


Output

GeeksforGeeks

Java Static Methods

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.  

public static void geek(String name)
{
 // code to be executed....
}
// Must have static modifier in their declaration.
// Return type can be int, float, String or user defined data type.

Memory Allocation of Static Methods

They are stored in the Permanent Generation space of heap as they are associated with the class in which they reside not to the objects of that class. But their local variables and the passed argument(s) to them are stored in the stack. Since they belong to the class, so they can be called to without creating the object of the class.

Important Points:  

  • Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName.methodName(args).
  • They are designed with the aim to be shared among all objects created from the same class.
  • Static methods can not be overridden, since they are resolved using static binding by the compiler at compile time. However, we can have the same name methods declared static in both superclass and subclass, but it will be called Method Hiding as the derived class method will hide the base class method.

Below is the illustration of accessing the static methods: 

Java




// Example to illustrate Accessing
// the Static method(s) of the class.
import java.io.*;
 
class Geek {
 
    public static String geekName = "";
 
    public static void geek(String name)
    {
        geekName = name;
    }
}
 
class GFG {
    public static void main(String[] args)
    {
 
        // Accessing the static method geek()
        // and field by class name itself.
        Geek.geek("vaibhav");
        System.out.println(Geek.geekName);
 
        // Accessing the static method geek()
        // by using Object's reference.
        Geek obj = new Geek();
        obj.geek("mohit");
        System.out.println(obj.geekName);
    }
}


Output

vaibhav
mohit

Note:

Static variables and their values (primitives or references) defined in the class are stored in PermGen space of memory. 

Frequently Asked Questions 

1. What if static variable refers to an Object? 

static int i = 1;
static Object obj = new Object();

In the first line, the value 1 would be stored in PermGen section. In second line, the reference obj would be stored in PermGen section and the Object it refers to would be stored in heap section.

2. When to use static methods? 

  • When you have code that can be shared across all instances of the same class, put that portion of code into static method.
  • They are basically used to access static field(s) of the class.

3. Difference Between Instance method vs Static method

  • Instance method can access the instance methods and instance variables directly.
  • Instance method can access static variables and static methods directly.
  • Static methods can access the static variables and static methods directly.
  • Static methods can’t access instance methods and instance variables directly. They must use reference to object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to.
     


Previous Article
Next Article

Similar Reads

Understanding storage of static methods and static variables in Java
In every programming language, memory is a vital resource and is also scarce. Hence the memory must be managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtu
6 min read
Understanding "static" in "public static void main" in Java
Following points explain what is "static" in the main() method: main() method: The main() method, in Java, is the entry point for the JVM(Java Virtual Machine) into the java program. JVM launches the java program by invoking the main() method. Static is a keyword. The role of adding static before any entity is to make that entity a class entity. It
3 min read
Difference between static and non-static method in Java
A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access any static method and static variable, without cr
6 min read
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the vari
4 min read
Why non-static variable cannot be referenced from a static method in Java
Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let's discuss why non-static vari
4 min read
Class Loading and Static Blocks Execution Using Static Modifier in Java
Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at “CLASS LOADING TIME” Execution Order: There is an order in which static block/method/variable gets initialized. Static BlockStatic Vari
3 min read
Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kind
4 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instan
5 min read
Instance Methods in Java
Instance Methods are the group of codes that performs a particular task. Sometimes the program grows in size, and we want to separate the logic of the main method from other methods. A method is a function written inside the class. Since java is an object-oriented programming language, we need to write a method inside some classes. The important po
5 min read
Java Unnamed Classes and Instance Main Methods
Java has introduced a significant language enhancement in Java Enhancement Proposal (JEP) 445, titled "Unnamed Classes and Instance Main Methods". This proposal aims to address the needs of beginners, making Java more accessible and less intimidating. Let's delve into the specifics of this proposal and understand how it simplifies the learning curv
7 min read
Can we Overload or Override static methods in java ?
Let us first define Overloading and Overriding. Overriding: Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in the superclass (or base class). The implementation to be executed is decided at run-time and a decision is made accor
5 min read
Why can't static methods be abstract in Java?
In Java, a static method cannot be abstract. Doing so will cause compilation errors.Example: Java Code // Java program to demonstrate // abstract static method import java.io.*; // super-class A abstract class A { // abstract static method func // it has no body abstract static void func(); } // subclass class B class B extends A { // class B must
3 min read
Using Instance Blocks in Java
The instance block can be defined as the name-less method in java inside which we can define logic and they possess certain characteristics as follows. They can be declared inside classes but not inside any method. Instance block logic is common for all the objects. Instance block will be executed only once for each object during its creation. Illu
3 min read
Instance Control Flow in Java
This article will explain how Instance Control Flow takes place whenever objects are created. Instance Control Flow In Normal Class Whenever we are executing a java .class file, 1st Static Control Flow will be executed. In the Static Control Flow, if we are creating an object the following sequence of steps will be executed as part of Instance Cont
7 min read
How to Execute Instance Initialization Block (IIB) without Creating Object in Java?
In a Java program, operations can be performed on methods, constructors, and initialization blocks. Instance Initialization Blocks or IIB are used to initialize instance variables. We know that the instance block is the name-less method in java inside which we can define logic and they possess certain characteristics. Instance block logic is common
3 min read
Difference Between Object and Instance in Java
The object is an instance of a class. A class is like a blueprint or template that defines the properties and behavior of objects. When we create an object we are creating an instance of that class. Object in JavaThe object is an instance of a class. A class is a blueprint or template that describes the behavior and properties of the objects of the
3 min read
Instance Variable Hiding in Java
One should have a strong understanding of this keyword in inheritance in Java to be familiar with the concept. Instance variable hiding refers to a state when instance variables of the same name are present in superclass and subclass. Now if we try to access using subclass object then instance variable of subclass hides instance variable of supercl
2 min read
Instance Initialization Block (IIB) in Java
In a Java program, operations can be performed on methods, constructors, and initialization blocks. Instance Initialization Blocks or IIBs are used to initialize instance variables. So firstly, the constructor is invoked and the java compiler copies the instance initializer block in the constructor after the first statement super(). They run each t
3 min read
Instance variable as final in Java
Instance variable: As we all know that when the value of variable is varied from object to object then that type of variable is known as instance variable. The instance variable is declared inside a class but not within any method, constructor, block etc. If we don’t initialize an instance variable, then JVM automatically provide default value acco
3 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Static Control Flow in Java
Static Control Flow decides the sequence of activities/steps that will be executed in order when we run a java class that contains static variables, methods, and blocks. This article will explain how static control flow occurs whenever a Java program is executed. Prerequisite: Static Blocks The Static Control Flow mechanism performs the following 3
4 min read
Static method in Interface in Java
Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementatio
2 min read
Static Block and main() method in Java
In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading. This is illustrated well in the following example: // Java program to demonstrate that static // block is executed before main() class staticExample { // static block stati
2 min read
Initialize a static map in Java with Examples
In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Method 1: Creating a static map variable. Instantiating it in a static block. Below is the implementation of the above approach: // Java program to creat
1 min read
Initialize a static Map using Stream in Java
In this article, a static map is created and initialized in Java using Stream. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Stream In Java Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of
2 min read
Initialize a static Map using Java 9 Map.of()
In this article, a static map is created and initialised in Java using Java 9. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Java 9 feature - Map.of() method In Java 9, Map.of() was introduced which is a convenient way to create instances of Map
2 min read
Initialize a static Map in Java using Double Brace Initialization
In this article, a static map is created and initialised in Java using Double Brace Initialization. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Double Brace Initialization In Double Brace Initialization: The first brace creates a new Anonymous
2 min read
Constructor Overloading with Static Block in Java
In Java, Constructor is a block of codes similar to the method that is used to initialize the object’s state. A constructor is invoked at the time of object or instance creation. Each time an object is created using a new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of
4 min read
Why a Constructor can not be final, static or abstract in Java?
Prerequisite: Inheritance in Java Constructor in java is a special type of method which is different from normal java methods/ordinary methods. Constructors are used to initialize an object. Automatically a constructor is called when an object of a class is created. It is syntactically similar to a method but it has the same name as its class and a
6 min read
What is Class Loading and Static Blocks in Java?
Class Loading is the process of storing the class-specific information in the memory. Class-specific information means, information about the class members, i.e., variables and methods. It is just like that before firing a bullet, first, we need to load the bullet into the pistol. Similarly, to use a class first we need to load it by a class loader
3 min read
Article Tags :
Practice Tags :